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.
vector<int> plusOne(vector<int> &digits) {
int carry = 0;
vector<int> nums;
for(int i=digits.size()-1; i >=0; i--)
{
int one = i == digits.size()-1 ? 1 : 0;
int d = (digits[i] + one + carry) % 10;
carry = (digits[i] + one + carry) / 10;
nums.insert(nums.begin(), d);
}
//don't forget carry for case {9}
if (carry > 0)
nums.insert(nums.begin(), 1);
return nums;
}
No comments:
Post a Comment