I was working on a leetcode question in c++ you can see the question properly - https://leetcode.com/problems/plus-one/
I was doing it again with a second approach where I will manually increase the value through a recursive call. It was getting an error only on leetcode compiler that -
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000250 overflowed to 0x60200000024c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
It was when we passed a vector only with a single value i.e. 9 It was running in my computer but not on leet code and I can't understand the bug. the code is-
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> incre(vector<int> &digits, int len)
{
if (digits[len - 1] != 9 && len != 0)
{
// if there is number before it which is not 9
digits[len] = 0;
digits[len - 1]++;
}
else if (len == 0)
{
// cout << "in zero loop-" << len << endl;
// if no nmber then we have to add before it
digits[len] = 0;
vector<int>::iterator iter = digits.begin();
digits.insert(iter, 1, 1);
}
else if (digits[len - 1] == 9)
{
// if the last number is again 9
// cout << "in recursive loop-" << len << endl;
digits[len] = 0;
digits = incre(digits, len - 1);
}
else
{
cout << "Something else occures" << endl;
}
return digits;
}
vector<int> plusOne(vector<int> &digits)
{
if (digits.back() != 9)
{
digits.back()++;
}
else
{
digits = incre(digits, digits.size() - 1);
}
return digits;
}
};
int main()
{
vector<int> digits{9};
// vector<int> digits{2,4,3,1, 9, 9};
// vector<int> digits{2,4,3,1, 5, 8};
// vector<int> digits{9, 9, 9, 9, 9, 9, 9, 9, 9};
vector<int> res;
Solution s;
res = s.plusOne(digits);
for (auto i : res)
{
cout << i << " ";
}
return 0;
}
you can copy run the whole code as I have given the whole code. The error occurs when I use the first test case - vector digits{9};.I know there are better approaches but I wanted to do it manually for practicing recursion. It would be very helpful if someone could point out the bug. Thanks in advance and sorry for grammatical mistakes.