[英]I'm getting an out of range error on my Leetcode program
So, I'm working on a relatively simple program on leetcode ( https://leetcode.com/problems/plus-one/ ).所以,我正在 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.给定一个大的 integer,表示为 integer 数组数字,其中每个数字 [i] 是 integer 的第 i 个数字。数字按从左到右的顺序从最高有效位到最低有效位排序。 The large integer does not contain any leading 0's.大 integer 不包含任何前导 0。
Increment the large integer by one and return the resulting array of digits.将较大的 integer 递增 1 并返回生成的数字数组。
Example: if digits = [1,2,3] then after digits = [1,2,4], because 123 + 1 = 124.示例:如果数字 = [1,2,3],则在数字 = [1,2,4] 之后,因为 123 + 1 = 124。
Anyways my code works for all the inputs I've tried except when the array consists of all 9's.无论如何,我的代码适用于我尝试过的所有输入,除非数组由全 9 组成。 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;
}
};
If all elements are 9, all elements will be removed by this part:如果所有元素都是 9,则这部分将删除所有元素:
if(digits.at(i) == 9)
{
digits.pop_back();
zeroCount++;
}
Therefore, the condition digits.at(index) < 9
becomes invalid after this operation.因此,条件digits.at(index) < 9
在此操作后变为无效。
This condition should be .digits.empty() && digits.at(index) < 9
to avoid this error.此条件应为.digits.empty() && digits.at(index) < 9
以避免此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.