So, I'm working on a relatively simple program on leetcode (https://leetcode.com/problems/plus-one/). I'll copy the description below:
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example: if digits = [1,2,3] then after digits = [1,2,4], because 123 1 = 124.
Anyways my code works for all the inputs I've tried except when the array consists of all 9's. I'm not sure why but I get an out of range error:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
I know that my code so far may not be the most optimal but I'd like to get it right my way before I attempt any sort of optimizing. I'll include my code below:
class Solution {
public:
vector<int> plusOne(vector<int>& digits)
{
if(digits.at(digits.size()-1) < 9)
{
digits.at(digits.size()-1) = 1;
}
else
{
int zeroCount = 0;
int index = 0;
for(int i = digits.size()-1; i >= 0;--i)
{
if(digits.at(i) == 9)
{
digits.pop_back();
zeroCount ;
}
else
{
index = i;
break;
}
}
if(digits.at(index) < 9)
{
digits.at(index) = 1;
for(int i = 0; i < zeroCount; i)
{
digits.push_back(0);
}
}
else
{
digits.push_back(1);
for(int i = 0; i < zeroCount; i)
{
digits.push_back(0);
}
}
}
return digits;
}
};
CodePudding user response:
If all elements are 9, all elements will be removed by this part:
if(digits.at(i) == 9)
{
digits.pop_back();
zeroCount ;
}
Therefore, the condition digits.at(index) < 9
becomes invalid after this operation.
This condition should be !digits.empty() && digits.at(index) < 9
to avoid this error.