알고리즘/LeetCode

[LeetCode/easy/Array] Plus One

녕이 2022. 8. 16. 16:40
728x90

 

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

 

올림 수 하나를 두고 진행한다.

만약 9라면 +1이 되면 10이 되어 자릿수가 늘어난다. 그러므로 이 값은 0으로 바꿔주고 올림수를 true로 변경해준다.

9가 아니면 그냥 +1을 진행하고 올림수는 false로 변경해준다.

모두 끝났는데, 만약 c(올림수) == true 라면 1을 붙여줘야 한다. 그런데 앞에 붙이는 것보단 뒤에 붙이는 게 편하니까 붙이고 뒤집어준다.

 

vector<int> plusOne(vector<int>& digits) {
    bool c = true; //1은 올림수
    for(int i=digits.size()-1; i>=0; i--){
        int n = digits[i];
        if(c == false) break;
        if(n + 1 > 9){
            digits[i] = 0;
            c = true;
        }else{
            digits[i] = n + 1;
            c = false;
        }
    }
    if(c == true) {
        digits.push_back(1);
        reverse(digits.begin(), digits.end());
    }
    return digits;
}

 

 

 

728x90