跳转至

66.Plus One

Tags: Easy Array

Links: 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.

Answer:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int extra = 0;
        int n = digits.size();
        vector<int> v(n, 0);
        v[0] = 1;
        reverse(digits.begin(), digits.end());

        for (int i = 0; i < n; ++i){
            int tmp = digits[i] + v[i] + extra;
            extra = tmp / 10;
            digits[i] = tmp % 10;
        }
        if (extra != 0)
            digits.push_back(extra);

        reverse(digits.begin(), digits.end());

        return digits;
    }
};
# run result
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Plus One.
Memory Usage: 8.6 MB, less than 91.80% of C++ online submissions for Plus One.