子弹分发
1、题目描述:
https://blog.csdn.net/goushaoping04/article/details/1519208
2、思路:
按照题目描述的方式,将每个士兵的手中的子弹同时拿出一半给下一个人,这个过程需要推导至一步一步遍历的方式。主要就是要解决下一个士兵的一半的问题,按步遍历这时下一个士兵已经加上了上一个士兵的一半,这时需要保存好下一个士兵当时的子弹数量nextNum ,用这个数量来计算需要移交给他下一个士兵的子弹数目。
3、代码:
class test1 { public static void main(String[] args) { int[] a = {10, 2, 8, 22, 16, 4, 10, 6, 14, 20}; distributeBullet(a); // int[] a = {14, 14, 14, 14, 14, 14, 14, 14, 14, 14}; // System.out.println(isEqual(a)); } public static void distributeBullet(int[] a) { int count = 0; while (!isEqual(a)) { jiShu(a); //提前保存好a[9] int num10 = a[9]; int temp = a[0] / 2; // int nextNum=0; for (int i = 0; i < a.length; i++) { if (i != 9) { int nextNum = a[i + 1]; a[i] = a[i] - temp; a[i + 1] = a[i + 1] + temp; temp = nextNum / 2; } else { a[9] -= temp; a[0] += temp; } } count++; System.out.print(count + ":"); for (int i = 0; i < a.length; i++) { if (i == a.length - 1) { System.out.println(a[i]); } else { System.out.print(a[i] + " "); } } } } public static boolean isEqual(int[] a) { int temp = a[0]; for (int i = 1; i < a.length; i++) { if (a[i] != temp) { return false; } } return true; } public static void jiShu(int[] a) { //遍历数组,是奇数就+1 for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 1) { a[i] += 1; } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)