알고리즘/리트코드

LeetCode 66 Plus One

고구마와 감자 2022. 4. 10. 20:20

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

풀이 참조: https://the-dev.tistory.com/55

public int[] plusOne(int[] digits) {
        int carry =1 ;
        int index = digits.length -1;
        while (index >= 0 && carry > 0) {
            digits[index] = (digits[index] + 1) % 10;
            carry = (digits[index] == 0) ? 1: 0;
            index--;
        }
        if (carry > 0) {
            digits = new int[digits.length +1];
            digits[0] = 1;
        }
        return digits;
}

 

 

뒷자리 숫자만 바꾸고 저장하는데 % 10을 해서 두자리이면 뒷자리만 저장되게 함. 

그리고 그 뒷자리가 0이면 carry를 1로 해서 그 다음 자리에 1을 더해 증가시킨다. 

 

다 끝났는데 아직도 carry 가 1이라면 숫자 앞자리가 늘어나야 하고, 뒤는 0 index 빼고는 0이다. 

따라서 1 증가한 배열(0으로초기화됨)을 만들고 index 0만 1로 바꾼다.