알고리즘/LeetCode

[LeetCode] 66. Plus One

HYJJ 2022. 6. 10. 20:04

문제 링크 : https://leetcode.com/problems/plus-one/

 

Plus One - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

배열이 주어지는데 각 배열은 i번째 자리의 수이다.

이 수에 1을 더한 값을 배열로 리턴하면 된다.

 

 

처음에 생각한 코드는 아래와 같다.

import java.lang.*;

class Solution {
    public int[] plusOne(int[] digits) {
        int ans = 0;
        int len = digits.length;
        
        for(int i=0; i<len; i++) {
            int num = digits[i];
            ans += num*Math.pow(10, len-i-1);
        }
        ans ++;
        
        String s = Integer.toString(ans);
        int ansArr[] = new int[s.length()]; 
        
        for(int i=0; i<s.length(); i++) {
            String tmp = s.substring(i,i+1);
            int n = Integer.parseInt(tmp);
            ansArr[i] = n;    
        }
        
        return ansArr;
    }
}

 

이렇게 했더니 테스트 케이스 중에서 runtime error 중 numberformat이 맞지 않는 에러가 발생하였다. 

생각을 다시 해봤을 때 int의 범위수가 넘어가는 수는 고려를 안한 것으로 밝혀졌다. 

digits의 길이가 100까지니 100자리 수 까지 생각해야 하는 것이다.

 

float을 int로 바꿔야 하나.. 생각해보니 잘 모르겠다.

다시 한번 생각해보려고 한다.