题目:
小明从糖果盒中随意抓一把糖果,每次小明会取出一半的糖果分给同学们。当糖果不能平均分配时,小明可以从糖果盒中(假设盒中糖果足够)取出一个或放回一个糖果,小明至少需要多少次(取出放回和平均分配均记一次)能将手中糖果分至只剩一颗。
输入描述
抓取糖果数(小于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;
}
}