728x90
https://leetcode.com/problems/plus-one/
올림 수 하나를 두고 진행한다.
만약 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
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/Array] Pascal's triangle (0) | 2022.08.16 |
---|---|
[LeetCode/easy/Array] Merge Sorted Array (0) | 2022.08.16 |
[LeetCode/easy/Array] Search Insert Position (0) | 2022.08.16 |
[LeetCode/easy/Array] Remove Element (0) | 2022.08.16 |
[LeetCode/easy/Array] Remove Duplicates from Sorted Array (0) | 2022.08.16 |