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

原文链接: https://www.cnblogs.com/dysjtu1995/p/12584888.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    66. Plus One

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338181

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:29
下一篇 2023年3月1日 下午11:30

相关推荐