Algorithm/LeetCode

2160. Minimum Sum of Four Digit Number After Splitting Digits

JunGi Jeong 2023. 3. 31. 17:45

 

https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/

 

Minimum Sum of Four Digit Number After Splitting Digits - LeetCode

Can you solve this real interview question? Minimum Sum of Four Digit Number After Splitting Digits - You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Le

leetcode.com

문제파악 및 재정의

정확히 4자리로 구성된 양의 정수 num이 제공됩니다.
num에서 찾은 숫자를 사용하여 num을 두 개의 새로운 정수 new1과 new2로 나눕니다.
new1 및 new2에는 선행 0이 허용되며 num에 있는 모든 숫자를 사용해야 합니다.

자료구조 및 알고리즘 선택

구현
1000 [1][0][0][0] -> 1 0 0 0 -> 0 0 0 1 except 0
1954 [1][9][5][4] -> 9 5 4 1 -> 작은 숫자 2개를 십진수로 -> [1][] [4][]
2223 [2][2][2][3]
class Solution {
    public int minimumSum(int num) {
        char[] temp = Integer.toString(num).toCharArray();
        Arrays.sort(temp);
        int first = 0;
        int second = 0;
        for(int idx =0; idx < temp.length; idx++){
            if(temp[idx] != '0'){
                if(idx == 0){
                    first += Integer.valueOf(temp[idx]  - '0') * 10;
                }else if(idx == 1){
                    second += Integer.valueOf(temp[idx] - '0') * 10;
                }else if(idx ==2){
                    first += Integer.valueOf(temp[idx]  - '0');
                }else if(idx == 3){
                    second += Integer.valueOf(temp[idx]  - '0');
                }
            }
        }
        return first + second;
    }
}

 

다른사람 코드

https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/solutions/3009974/easy-java-solution/?languageTags=java

int[] digits = new int[4];
        int i=0;
        while(i<=3)
        {
            digits[i++] = num%10;
            num/=10;
        }
        Arrays.sort(digits);
        // digits[0] at ten's place and digits[2] at one's place makes the first number
        // digits[1] at ten's place and digits[3] at one's place makes the second number
        return digits[0]*10+digits[2]+digits[1]*10+digits[3];