爱奇艺第一题幸运id

版权声明:原创文章,转载需注明转载出处! https://blog.csdn.net/zhoumingsong123/article/details/82715436
//题目:
//输入一个6位数字的字符串,幸运数字串要求前三位之和等于后三位数字之和
//,求让这个字符串变为幸运字符串的最小操作次数。

//AC73%的思想是:多次修改字符串之和较小的三位数字来让其和较大的相等。
//漏解:比如888999最少修改次数是1,不是3,可以直接将其变成888996而不是999999。

988025 应该为2 ,不是3,把9改成0,把0改成9
//启发:每次选择让两者差距最小的数字修改。

//如题:
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // write your code here

        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String str = sc.next();

            String str1 = str.substring(0, 3);
            String str2 = str.substring(3, 6);

            int sum1 = 0;
            int sum2 = 0;
            int cha1[] = new int[3];
            int cha2[] = new int[3];

            int cha3[] = new int[3];

            int cha4[] = new int[3];

            for (int i = 0; i < 3; i++) {

                int num1 = Integer.parseInt(String.valueOf(str1.charAt(i)));
                int num2 = Integer.parseInt(String.valueOf(str2.charAt(i)));
                sum1 = sum1 + num1;
                sum2 = sum2 + num2;

                cha1[i] = 9 - num1;
                cha3[i] = num1;
                cha2[i] = 9 - num2;
                cha4[i] = num2;
            }

            int re = Math.abs(sum2 - sum1);

            Arrays.sort(cha1);
            Arrays.sort(cha2);
            Arrays.sort(cha3);
            Arrays.sort(cha4);

            if (sum2 == Math.max(sum1, sum2)) {

                int index1 = 2;
                int index2 = 2;
                int count = 0;

                while (re > 0) {

                    if (cha1[index1] > cha4[index2]) {//sum1 +
                        re = re - cha1[index1];
                        index1--;
                    } else {
                        re = re - cha4[index2];//sum2 -
                        index2--;
                    }


                    count = count + 1;


                }


                System.out.println(count);

            } else {

                int index1 = 2;
                int index2 = 2;
                int count = 0;

                while (re > 0) {

                    if (cha2[index1] > cha3[index2]) {//sum2 +
                        re = re - cha2[index1];
                        index1--;
                    } else {
                        re = re - cha3[index2];// sum1 -
                        index2--;
                    }


                    count = count + 1;


                }


                System.out.println(count);

            }


        }


    }
}

猜你喜欢

转载自blog.csdn.net/zhoumingsong123/article/details/82715436