# 【LeetCode】 66. Plus One ## Description > Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit. > You may assume the integer does not contain any leading zero, except the number 0 itself. > 給一個不是空的陣列代表一個非負整數的每一位數,請將這個整數加一。 > 最高有效位元被存在list的頭,陣列中每一個值都只能表示一位元。 > 你可以假設不會有任何多餘的零,除非這個數字剛好等於零。 ## Example: ``` Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2: Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. ``` ## Solution * 做大數加法的概念去做即可。 * 先將個位數加一,然後慢慢往高位元檢查是否需要進位。 * 如果原本只有`n`位,因為進位跑到`n+1`位的話,要使用`insert`去補一位數。 ### Code ```C++=1 class Solution { public: vector<int> plusOne(vector<int>& digits) { int temp = digits.size()-1; digits[temp]++; while(1) { if(digits[temp]>=10) { digits[temp]-=10; temp--; if(temp<0) { digits.insert(digits.begin(),1); break; } else digits[temp]++; } else break; } return digits; } }; ``` ###### tags: `LeetCode` `C++`