50. Plus One-Leetcode

  1. Plus One My Submissions QuestionEditorial Solution
    Total Accepted: 98403 Total Submissions: 292594 Difficulty: Easy
    Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

思路:
比较简单,有进位,当前为置为0,判断下一位+1是否为10,如此继续
最后看最高位是否进位,有进位,插入新的1
时间复杂度:O(n)
空间:O(1)

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {//这里没说是否修改digits,也没定义为const,所以可以不用另外用存储空间
        int n=digits.size();
        int k=n-1;
        while(k>=0&&digits[k]+1>=10)digits[k--]=0;
        if(k>=0)  digits[k]+=1;
        else digits.insert(digits.begin(),1);
        return digits;
};
原文地址:https://www.cnblogs.com/freeopen/p/5482916.html