N

(Leet Code c++)Plus One 본문

Leet Code 알고리즘

(Leet Code c++)Plus One

naeunchan 2021. 7. 9. 09:56
728x90
반응형

66. 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.

 

Example 1:

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

Example 2:

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

Example 3:

Input: digits = [0] Output: [1]

 

주어진 digits 벡터에서 + 1을 한 값을 다시 리턴하면 된다.

참조자로 digits가 주어졌으므로 그대로 digits를 리턴한다.

 

digits의 뒤부터 확인하여 1을 더해주도록 한다.

맨 뒷자리의 수가 9라면 0을 만들어주고 앞자리에 1을 더해줘야 한다.

이를 check를 통해 확인하면서 + 1을 하였다.

또한, [0]과 같은 경우가 주어졌을 때, [1, 0]을 리턴해야 하므로,

i == 0 인 조건을 걸어 맨 앞자리에 1을 추가했다.

 

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        bool check = false;
        
        for(int i = digits.size() - 1; i >= 0; i--){
            if(!check){
                if(digits[i] == 9){
                    digits[i] = 0;
                    
                    if(i == 0){
                        digits.insert(digits.begin(), 1);
                    }
                }
                else{
                    digits[i]++;
                    check = true;
                }
            }
            else{
                break;
            }
        }
        
        return digits;
    }
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code c++)Sqrt(x)  (0) 2021.07.09
(Leet Code c++)Add Binary  (0) 2021.07.09
(Leet Code c++)Length of Last Word  (0) 2021.07.09
(Leet Code c++)Container With Most Water  (0) 2021.07.08
(Leet Code c++)Maximum Subarray  (0) 2021.07.08