Java硬币翻转倍数递增试算实例
时间:2021-09-29 08:39:22
//有何不足或者问题希望能够得到各位的多多指正,不胜感激
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();
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MyBatis快速入门
![](https://img.aspxhome.com/file/2023/5/62155_0s.png)
通过Java连接SQL Server数据库的超详细操作流程
![](https://img.aspxhome.com/file/2023/8/63098_0s.png)
java中删除 数组中的指定元素方法
Zookeeper事务日志预分配空间解读
Java调用Shell命令和脚本的实现
C#通过PInvoke调用c++函数的备忘录的实例详解
Spring Boot与Spark、Cassandra系统集成开发示例
Java8中Optional类型和Kotlin中可空类型的使用对比
SpringBoot解决跨域请求拦截问题代码实例
![](https://img.aspxhome.com/file/2023/4/67964_0s.png)
关于Maven的使用,这些你都真的了解么
Java应用多机器部署解决大量定时任务问题
![](https://img.aspxhome.com/file/2023/1/58691_0s.png)
Java Stream流零基础教程
Java二维数组与动态数组ArrayList类详解
Studio 编译报错:compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.的解决办法
![](https://img.aspxhome.com/file/2023/0/81320_0s.png)
Web容器启动过程中如何执行Java类
jQuery 动画效果代码分享
一篇带你解析入门LongAdder源码
![](https://img.aspxhome.com/file/2023/1/60401_0s.png)
java中javamail收发邮件实现方法
![](https://img.aspxhome.com/file/2023/4/68714_0s.png)
JavaSwing FlowLayout 流式布局的实现
![](https://img.aspxhome.com/file/2023/2/63802_0s.png)