来源:Leetcode
原帖:http://oj.leetcode.com/problems/plus-one/
题目:
Given a 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.
代码:
原帖:http://oj.leetcode.com/problems/plus-one/
题目:
Given a 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.
代码:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = 1;
int N = digits.size();
for (int i = N - 1; i >= 0 && carry; --i) {
int sum = carry + digits[i];
carry = sum / 10;
digits[i] = sum % 10;
}
if (carry == 1) { // insert 'carry = 1'
digits.insert(digits.begin(), 1);
}
return digits;
}
};
No comments:
Post a Comment