복's

[ LeetCode - 66 ] Plus One 본문

알고리즘/LeetCode

[ LeetCode - 66 ] Plus One

나복이 2023. 11. 3. 04:02
728x90

https://leetcode.com/problems/plus-one/description/

 

Plus One - LeetCode

Can you solve this real interview question? Plus One - You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-

leetcode.com

파이썬과 자바의 차이에 대해서 느끼게 되는 문제였다.


[ 📌 틀린 이유 ]

python의 경우에는 알아서 처리 해주는데 java의 경우에는 digits 배열의 길이가 100까지 올 수 있기 때문에 int, long의 범위를 초과하게 된다.

 

근데 나는 문자열 -> 숫자 -> 연산 -> 문자열 과정으로 문제를 풀려고 했는데 정수로 캐스팅 불가능한 숫자가 오니까ClassNumberFormat Runtime에러를 마주하게 되었다.


[ 📌 풀이 - python ]

문자 -> 숫자 -> 연산 -> 문자 순서로 진행 했다.

 

[ 📌 풀이 - java ]

주어진 배열을 그래도 사용 하였으며, 배열의 맨 뒤부터 계산해서 자리 올림해주었다.

배열의 맨 앞까지 도달하는 경우 ex) 999 -> 1000 길이가 1 더 긴 새로운 배열을 하나 만들어서 맨 앞에 요소에 1삽입 후 반환했다.


[ 📌 코드 - Python ]

"""
# Author    : Lee In Bok 
# Date      : 2023.11.02(Thu)
# Spend Time: 08m 13s
# Runtime   : 30 ms (Beats 97.37%)
# Memory    : 16.2 MB (Beats 38.4%)
# Algoritm  : String
"""

from typing import List

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        num = (int) (''.join(str(e) for e in digits)) + 1

        return list(map(int, str(num)))

s = Solution()
result = s.plusOne([1,2,3])

print(result)

[ 📌 코드 - Java ]

/**
* Author    : Lee In Bok 
* Date      : 2023.11.02(Thu)
* Spend Time: 02m 04s
* Runtime   : 0 ms (Beats 100%)
* Memory    : 40.4 MB (Beats 97.35%)
* Algoritm  : String
 */
 
public class Q66_PlusOne {
    public static void main(String[] args) {
        Solution s = new Solution();
        int[] result = s.plusOne(new int[]{9,9,9});

        for(int a : result){
            System.out.print(a + " ");
        }
    }
}

class Solution {
    public int[] plusOne(int[] digits) {
        for(int idx = digits.length - 1; idx >= 0; idx--){
            if(digits[idx] == 9){
                digits[idx] = 0;
            } else {
                digits[idx]++;
                return digits;
            }
        }

        int[] newArr = new int[digits.length + 1];
        newArr[0] = 1;

        return newArr;
    }
}

 

[ 📌 개선 코드 - Java ]

다른 사람의 코드를 보니까 똑같은 풀이지만 더 깔끔한 코드가 있었다.

if ~ else가 아니라 if문으로 끝내는 코드인데 더 간결하고 보기 좋은게 조건을 어떻게 설정하냐도 중요한 덕목인 것 같다.

for(int idx = digits.length - 1; idx >= 0; idx--){
    if(digits[idx] < 9){
        digits[idx]++;
        return digits;
    } 

    digits[idx] = 0;
}

[ 📌 결과 - Python ]

[ Result - Python ]

[ 📌 결과 - Java ]

[ Result - Java ]

 

728x90