20 Plus One

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.

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.

一道简答难度的加法题目,关键是对进位的处理。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
       
        int len = digits.size();
        int c = 0;
        
        vector<int> ans = digits;
        
        for(int i=len-1;i>=0;i--)
        {
            
            if(i == len -1 ){
                
                ans[i] = (digits[i] + 1 + c)%10;
                c = ( (digits[i] + 1) < 10 ) ? 0:1 ;
                
            } 
            else{
                
                ans[i] = (digits[i] + c)%10;
                c = ( (digits[i] + c) < 10 ) ? 0:1 ;
      
            } 
            
        }
        
     
        if(c==1) ans.insert(ans.begin(),1);
        
        return ans;
        
    }
};
posted @ 2019-08-22 16:35  孙小鸟  阅读(73)  评论(0编辑  收藏  举报