首页 > 代码库 > [Leetcode] Plus One

[Leetcode] Plus One

题目:

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.

 

Tag:

Array; Math

 

体会:

这道题就是遵循着正常加法的模式,就是99..9这样情况的时候,要在最前位插入一个1。

class Solution {public:    vector<int> plusOne(vector<int> &digits) {        // follow the basic maths, pay attention to 99..9        int n = digits.size();        for (int i = n - 1; i >= 0; i--) {            if ( digits[i] < 9) {                // safe, + 1 and end                digits[i]++;                return digits;            }             digits[i] = 0;        }        // if comes here, it is 99..9        digits.insert(digits.begin(), 1);        return digits;    }};

 

[Leetcode] Plus One