leetcode解题: Plus One (66)

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.

解法1:O(N)

很基本的算carry,digit的方法

C++
要注意c++ insert的用法是insert(iterator, obj), 如果是在头部插入,可以用insert(it.begin(), obj).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
if (digits.size() == 0) {
return digits;
}
int carry = 0;
int n = digits.size();
carry = (digits[n - 1] + 1) / 10;
digits[n - 1] = (digits[n- 1] + 1) % 10;
for (int i = n - 2; i >= 0; --i) {
int temp = (digits[i] + carry) % 10;
carry = (digits[i] + carry) / 10;
digits[i] = temp;
}
if (carry > 0) {
digits.insert(digits.begin(), carry);
}
return digits;
}
};

Java

1