//有何不足或者问题希望能够得到各位的多多指正,不胜感激
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(); } }
时间: 2024-09-22 09:48:48