分糖果问题

题目:
小明从糖果盒中随意抓一把糖果,每次小明会取出一半的糖果分给同学们。当糖果不能平均分配时,小明可以从糖果盒中(假设盒中糖果足够)取出一个或放回一个糖果,小明至少需要多少次(取出放回和平均分配均记一次)能将手中糖果分至只剩一颗。

输入描述
抓取糖果数(小于1000000),例如15

输出描述
最少分至一颗糖果的次数,例如5

示例
输入

15

输出

5

分析:
对于一个随机数N(N>=1),要么为奇数,要么为偶数。
(1)若为偶数,它的划分次数是随机数为(N/2)的划分次数 +1。
(2)若为奇数,我们需要比较 (N+1) 和(N-1)的划分次数,取两个当中最小值,因为取出和放回也要算一次操作,所以加上1。
这里采用递归思想进行划分。

参考代码:

import java.util.Scanner;

public class ShareCandy {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            int readNumber = scanner.nextInt();
            int count = share(readNumber, 0);
            System.out.println(count);
        }

    }

    private static int share(int number, int count) {
        if (number == 1) {
            return count;
        }
        int res;
        if (number % 2 != 0) {
            int add = share(number + 1, count + 1);
            int sub = share(number - 1, count + 1);
            if (add > sub) {
                res = sub;
            } else {
                res = add;
            }
        } else {
            res = share(number / 2, count) + 1;
        }

        return res;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值