July LeetCoding Challenge - 6

이선태·2020년 7월 7일
0

Leetcode challenge

목록 보기
6/8

Day 6

Plus One

문제

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

답(Java)

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

배열에 있는 수들을 하나의 숫자로 생각하고 1을 더했을 때 결과를 다시 배열로 나타내는 문제이다. 배열에 있는 숫자가 9 이하일 때는 단순히 1을 더하고 종료하면 된다. 배열에 있는 숫자가 9라면 현재 위치의 숫자를 0으로 하고 이전 위치로 이동하여 올림 수를 더해준다.
[9, 9, 9, 9]의 경우처럼 1을 더했을 때 자릿수가 증가할 수도 있다. 이때는 자릿수를 1 증가시킨 배열을 새로 생성하고 최상위 자리의 숫자를 1로 대입한다. 결과는 [1, 0, 0, 0, 0]가 될 것이다.

profile
퀀트 트레이딩, 통계에 관심이 많아요

0개의 댓글