您的位置 首页 > 腾讯云社区

历届试题 分糖果---AI那点小事

问题描述   有n个小朋友围坐成一圈。老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏:

  每个小朋友都把自己的糖果分一半给左手边的孩子。

  一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数。

  反复进行这个游戏,直到所有小朋友的糖果数都相同为止。

  你的任务是预测在已知的初始糖果情形下,老师一共需要补发多少个糖果。 输入格式   程序首先读入一个整数N(2

import java.util.Scanner; /* * 这是分糖果类 */ class Candle{ private int N; private int[] candle; private int count; /* * 这是构造方法 */ public Candle() { super(); Scanner in = new Scanner(System.in); N = in.nextInt(); this.count = 0; candle = new int[N]; for ( int i = 0 ; i < candle.length ; i++){ candle[i] = in.nextInt(); } in.close(); } /* * 分配一轮方法 */ public void Distribute_OneTime(){ int[] tmp = new int[this.N]; for ( int i = 0 ; i <tmp.length ; i++){ tmp[i] = this.candle[i] / 2; } for( int i = 0 ; i < N ; i++){ int j; if ( i == 0){ j = N-1; }else{ j = i-1; } this.candle[i] += tmp[j]; this.candle[i] -= tmp[i]; } } /* * 分配方法 */ public void Distribute(){ while(true){ if(IsSame()){ break; }else{ this.Distribute_OneTime(); this.AddOneCandle(); } } } /* * 奇数糖果加一方法 */ public void AddOneCandle(){ for ( int i = 0 ; i < N ; i++){ if (this.candle[i] % 2 != 0){ this.candle[i]++; this.count++; } } } /* * 判断数组是够全相等 */ public boolean IsSame(){ boolean flag = true; for ( int i = 0 ; i < N - 1 ; i++){ for ( int j = i+1 ; j < N ; j++){ if(this.candle[i] != this.candle[j]){ flag = false; break; } } if (flag == false){ break; }else{ continue; } } return flag; } public void Print_Count(){ System.out.print(count); } } /* * 这是测试类 */ public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Candle test = new Candle(); test.Distribute(); test.Print_Count(); } } ---来自腾讯云社区的---AI那点小事

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: