历届试题 分糖果

问题描述
  有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();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daipuweiai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值