Friday, April 26, 2013
Leetcode: Plus One in C++
Given a number represented as an array of digits, plus one to the number.
Solution:
vector<int> plusOne(vector<int> &digits) {
int carry = 0;
int len = digits.size();
vector<int> result(len+1,0);
for(int i=0;i<digits.size();i++)
{
if(i==0)
result[len-i] = digits[len-1-i] + 1 +carry;
else
result[len-i] = digits[len-1-i]+carry;
if(result[len-i]==10)
{
carry = 1;
result[len-i] = 0;
}
else
carry = 0;
}
if(carry==1)
result[0] =1;
else
result.erase(result.begin());
return result;
}
Labels:
Array and List
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment