Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

leetcode palindrome problem showing runtime error

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading