66. Plus One

Problem:

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.

思路

Solution (C++):

vector<int> plusOne(vector<int>& digits) {
    int n = digits.size(), carry = 1;
    for (int i = n - 1; i >= 0; --i) {
        digits[i] += carry;
        if (digits[i] == 10) { digits[i] = 0; carry = 1; }
        else carry = 0;
    }
    if (carry == 1)  {digits[0] = 1; digits.push_back(0); }
    return digits;
}

性能

Runtime: 4 ms  Memory Usage: 6.3 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

上一篇:项目总结66:真实项目Springboot继承kafka集群


下一篇:树转化成二叉树