Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has
[1, 2, 3]
the returned vector should be
[1, 2, 4]
as
123 + 1 = 124
.
vector<int> Solution::plusOne(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int i,carry = 1,p=0;
vector<int> result(A.size()+1,0);
// DO STUFF HERE. NOTE : length_of_array can be n1 OR n1 + 1.
for(i = A.size(); i > 0 ; i--)
{
int temp = A[i-1] + carry;
if(temp == 10){
result[i] = 0;
carry = 1;
}else
{
result[i] = temp;
carry = 0;
}
}
if(carry == 1)
result[i] = 1;
else{
int i = 0;
while(result[i++] == 0)
p++;
result.erase(result.begin(),result.begin()+p);
}
return result;
}
Comments
Post a Comment