#Leetcode# 66. Plus One

https://leetcode.com/problems/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 n = digits.size();
        int k = 0;
        vector<int> ans;
        ans.push_back((digits[n - 1] + 1) % 10);
        k = (digits[n - 1] + 1) / 10;
        for(int i = n - 2; i >= 0; i --) {
            ans.push_back((digits[i] + k) % 10);
            k = (digits[i] + k) / 10;
        }
        if(k) ans.push_back(1);
        int c = ans.size();
        for(int i = 0; i < c / 2; i ++) 
            swap(ans[i], ans[c - i - 1]);
        return ans;
    }
};

  

posted @ 2018-11-24 22:59  丧心病狂工科女  阅读(120)  评论(0编辑  收藏  举报