子弹分发

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;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/guoyu1/p/12416635.html