LeetCode 66. Plus One

margarin·2021년 3월 8일
0

알고리즘

목록 보기
12/13

문제

https://leetcode.com/problems/plus-one/
Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.

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

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

풀이

배열이지만 숫자로 생각해서 +1을 더하라는 문제이다.
끝.🥳

.........
그냥 1만 더하면 끝이 아니다.🤯
해당 자릿수의 숫자가 9라면 1을 더하고 자릿수를 증가시켜야한다..!🤭
배열의 맨 뒤부터 방문하여 해당 값이 9가 아니면 1을 증가시킨다.
만일 9라면 0으로 변경하고, 맨앞자리를 1로 변경 후, 자릿수 증가를 위해 0을 삽입한다.
즉 [9,9]라면 [1,0,0]이 되어야한다.

코드

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for (int i = digits.size() - 1; i >= 0; i--){
            if (digits[i] == 9) {
                digits[i] = 0;
            } else {
                digits[i]++;
                return digits;
            }
        }
        digits[0] = 1;
        digits.push_back(0);
        return digits;
    }
};
profile
화이팅 🥹

0개의 댓글