题目描述:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
这题给我们一个用数组表示的数字,让我们进行+1后还是用数组的形式返回。
解题思路:
这题的思路就是从数组的末尾开始遍历,对每个元素进行+1操作。不过要注意像9这样的进位后+1的特殊元素。
代码:
1 class Solution { 2 public: 3 vector<int> plusOne(vector<int>& digits) { 4 bool plusFlag=1; 5 for(int i=digits.size()-1;i>=0;i--){ 6 if(plusFlag==1){ 7 digits[i]+=1; 8 if(digits[i]==10){ 9 digits[i]=0; 10 if(i==0) 11 digits.insert(digits.begin(),1); 12 } 13 else 14 plusFlag=0; 15 } 16 else 17 break; 18 } 19 return digits; 20 } 21 };