17:Plus One

来源:互联网 发布:江歌案始末知乎 编辑:程序博客网 时间:2024/06/13 09:13

注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解

题目:Given a number represented as an array of digits, plus one to the number

代码如下:

//时间复杂度O(n),空间复杂度O(1)class Solution {public:        vector<int> plusOne(vector<int>& digits) {                add(digits, 1);                return digits;        }private:        // 0 <= digit <=9        void add(vector<int>& digits, int digit) {                int c = digit;                for (int i = digits.size() - 1; i >= 0; --i) {                        digits[i] += c;                        c = digits[i] / 10;                        digits[i] %= 10;                }                /*                for (auto it = digits.rbegin(); it != digits.rend(); ++it) {                        *it += c;                        c = *it / 10;                        *it %= 10;                }                */                if (c != 0) digits.insert(digits.begin(), c);        }};
0 0
原创粉丝点击