class Solution {
public:
bool isPalindrome(int x) {
int num, pal=0;
num=x;
if(num<0){
return false;
}
while(num!=0){
int b =num%10;
pal=(pal*10)+b;
num=num/10;
}
cout<<pal<<endl;
if(x==pal){
return true; //pal=3952 a=2593
}
else{
return false;
}
}
};
this is my solution of my leetcode problem and when I submit it, it shows,
Runtime Error
Line 11: Char 21: runtime error: signed integer overflow: 998765432 * 10 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:20:21
>Solution :
The error is occurring because during program execution, one of your integers (in this case it will be either num or pal) is being set to a value greater than its range (-2,147,483,648 <= v < 2,147,483,648, where v is the value you’re trying to store). This leads to a ‘wrap-around’ effect where the variable goes from a really large value to the smallest representable value.
To fix this, you should use a larger data type, like long long to represent num and pal to prevent the overflow.
For example:
class Solution {
public:
bool isPalindrome(int x) {
long long num, pal = 0;
num = x;
if (num < 0) {
return false;
}
while (num != 0) {
int b = num % 10;
pal = (pal * 10) + b;
num = num / 10;
}
if (x == pal) {
return true;
}
else {
return false;
}
}
};
Also, the cout statement is not needed on LeetCode.