1. 程式人生 > >愛奇藝第一題幸運id

愛奇藝第一題幸運id

//題目:
//輸入一個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); } } } }