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.
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Input: digits = [0]
Output: [1]
- 1 <= digits.length <= 100
- 0 <= digits[i] <= 9
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size();
int i = len-1;
int end = digits[i] + 1;
if (end == 10) {
int carry = 1;
while(carry) {
if (i == 0) {
digits.insert(digits.begin(), 0);
i++;
}
digits[i-1] ++;
digits[i] = 0;
if (digits[i-1] == 10)
i --;
else
carry = 0;
}
}
else
digits[i] = end;
return digits;
}
};
LeetCode๋ test case๋ก ์ฝ๋๋ฅผ runํ ํ์ submit์ ํ๋ฉด ์์ ๊ฐ์ด ์ฝ๋๊ฐ ์ฑ๊ณต์ ์ผ๋ก ๋์๊ฐ๋์ง ๋ณด์ฌ์ค๋ค. ์ฌ๋ฌ ๋ฒ์ ์๋๋ก ์๋ฌ๋ฅผ ๊ณ ์น๋ ค๊ณ ๋
ธ๋ ฅํด ๋ดค์ง๋ง ์ ๋์ง ์์์ ๋ค๋ฅธ ๋ถ๋ค์ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํด์ ๋ง์ง๋ง์ธ 7๋ฒ์ ์๋์์ success๋ฅผ ๋ฐ์๋ค. ์ธ์ ๊ฐ๋ ๋ค๋ฅธ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํ์ง ์๊ณ ๋ด ํ์ผ๋ก ํจ์จ์ ์ด๊ณ ๊น๋ํ ์ฝ๋๋ฅผ ์ธ ์ ์๋๋ก ์ด์ฌํ ๊ณต๋ถํด์ผ ๊ฒ ๋ค ๐ค๐ช๐ป
C++ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ(Standard Template Library) Vector class
- ํค๋ ํ์ผ: < vector >
- vector์ ์์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ํจ์: size()
- vector์ ์ฒซ๋ฒ์งธ ์์น๋ฅผ ๊ตฌํ๋ ํจ์: begin()
- vector์ ์์ ์ถ๊ฐ: insert(index, value)
vector<int> vec = {1, 2, 3, 4, 5}; cout << vec.size(); // 5 vec.insert(vec.begin(), 2); // vector์ ๋งจ ์์ ์์ 2 ์ฝ์
[์ถ์ฒ: https://coding-factory.tistory.com/596]