Java硬币翻转倍数递增试算实例
//有何不足或者问题希望能够得到各位的多多指正,不胜感激
import java.util.scanner;
/**
*
* @author cc 举例 100枚硬币,最初全部朝下,第一次将所有硬币反转过来, 第二次反转位置是2的倍数的硬币,
* 第三次反转3的倍数,.....执行一百次,问最终共有多少个硬币面朝上?
*
* 1.硬币正反使用数组 1、0表示,1表示正面,0表示反面;
*
*
* 100枚硬币的结果
int[] == 1100100001000000100000000100000000001000000000000100000000000000100000000000000001000000000000000000
result coin about 1 nums = 10
*/
public class cointurn {
private static int[] intcoins;
public static void main(string[] args) {
// todo auto-generated method stub
int coinnum = inputnum();
intcoins = new int[coinnum];
/*
* 初始化
*/
for (int i = 0; i < intcoins.length; i++) {
intcoins[i] = 0;// 初始化全部朝下,即背面0
}
doturncoin();
int resutltcoin = getcoinnum();
system.out.println("result coin about 1 nums = " + resutltcoin);// 输出最终正面朝上的个数
}
private static void doturncoin() {
/*
* 翻转操作
*/
for (int i = 1; i < intcoins.length; i++) {// 确定倍数
for (int j = i - 1; j < intcoins.length; j++) {// 循环翻转
if (j % i == 0) { // 硬币序列数是当前次数的倍数,则翻转
if (intcoins[j] == 0) {
intcoins[j] = 1;
} else {
intcoins[j] = 0;
}
}
}
}
}
private static int getcoinnum() {
int countnum = 0;// 记录最终硬币正面个数
stringbuffer strb = new stringbuffer();
for (int a : intcoins) {
strb.append(a + "");
if (1 == a)
countnum++;
}
system.out.println("int[] == " + strb);// 输出数组的结果
return countnum;
}
/*
* coin number
*/
private static int inputnum() {
system.out.println("input coin num: ");
scanner input = new scanner(system.in);
return input.nextint();
}
}
推荐阅读