patterncppMinor
Given a number represented as an array of digits, plus one to the number
Viewed 0 times
representednumberthearraydigitsplusonegiven
Problem
Given a number represented as an array of digits, plus one to the
number.
The following is my C++ code:
number.
input expected
[8,9,9,9] [9,0,0,0]
[1,0,0,0,0] [1,0,0,0,1]
[9,8,7,6,5,4,3,2,1,0] [9,8,7,6,5,4,3,2,1,1]The following is my C++ code:
vector plusOne(vector &digits)
{
vector result;
vector::iterator it;
int plus = 1;
for (it = digits.end() - 1; it >= digits.begin(); --it)
{
int sum = *it + plus;
if (sum > 9)
{
plus = 1;
result.push_back(0);
}
else
{
result.push_back(sum);
plus = 0;
}
}
if (plus==1)
{
result.push_back(1);
}
reverse(result.begin(), result.end());
return result;
}Solution
Since you are returning a result.
Pass the parameter by const reference so that you don't accidentally modify it:
The less than operator is not defined for iterators.
You are just getting lucky.
To iterate over a container in the reverse direction use
To help with efficiency you could reserve space in your result:
Personally I would have refactored:
the body into:
Pass the parameter by const reference so that you don't accidentally modify it:
vector plusOne(vector const& digits)The less than operator is not defined for iterators.
You are just getting lucky.
for (it = digits.end() - 1; it >= digits.begin(); --it)To iterate over a container in the reverse direction use
rbegin() and rend()for (it = digits.rbegin(); it != digits.rend(); ++it)To help with efficiency you could reserve space in your result:
result.reserve(digits.size()+1); // The +1 is for cases where the result overflows.
// Note: reserve() does not change the size of the
// vector just the underlying capacity.Personally I would have refactored:
if (sum > 9)
{
plus = 1;
result.push_back(0);
}
else
{
result.push_back(sum);
plus = 0;
}the body into:
plus = (sum == 10) ? 1 : 0
sum = (sum == 10) ? 0 : sum;
result.push_back(sum);Code Snippets
vector<int> plusOne(vector<int> const& digits)for (it = digits.end() - 1; it >= digits.begin(); --it)for (it = digits.rbegin(); it != digits.rend(); ++it)result.reserve(digits.size()+1); // The +1 is for cases where the result overflows.
// Note: reserve() does not change the size of the
// vector just the underlying capacity.if (sum > 9)
{
plus = 1;
result.push_back(0);
}
else
{
result.push_back(sum);
plus = 0;
}Context
StackExchange Code Review Q#23666, answer score: 4
Revisions (0)
No revisions yet.