Thursday, August 13, 2015

Leetcode: Plus ONE (4ms) solution

PROBLEM:

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.

Analysis:

Plus one from the end of the array. Key is to process the carrier from the addition.

///////////////////////////////////////////////////
// code 4ms
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size(), i = n - 1, c = 1;

while (i>-1 && c == 1){
int tmp = c;
            c = digits[i] + 1>9 ? 1 : 0;
digits[i] = (tmp + digits[i]) % 10;

i--;
}
//c is still 1
if (c == 1){
digits[0] = 1;
digits.push_back(0);
}
return digits;
}
};








No comments:

Post a Comment