凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 66. Plus One

分类:algorithm| 发布时间:2017-03-21 08:57:00


题目

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

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

题意

给出一个以一组数值表示非负数字,求出加一后的结果。

解法

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        bool carry = true;
        for (int i = digits.size() - 1; carry && i >= 0; --i) {
            ++digits[i];
            if (digits[i] == 10) {
                digits[i] -= 10;
                carry = true;
            } else {
                carry = false;
            }
        }

        if (carry) {
            digits.insert(digits.begin(), 1, 1);
        }

        return digits;
    }
};