'Leetcode Q9 Palindrome Number same code works in Java but not in C++
I tried solving this problem: https://leetcode.com/problems/palindrome-number/ using code:
class Solution {
public:
bool isPalindrome(int x) {
int rev = 0;
int temp = x;
while(temp != 0 && temp > 0){
rev = rev* 10;
rev = rev + temp%10;
temp = temp/10;
}
if (rev == x){
return true;
}
else{
return false;
}
}
};
and got this error in C++:
Line 7: Char 22: runtime error: signed integer overflow: 998765432 * 10 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:16:22
The logically same code runs perfectly in Java though. Both java and c++ have int data type ranging from - 2^31 to 2^31-1 (Source: https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm, https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html#:~:text=int%3A%20By%20default%2C%20the%20int,value%20of%20232%2D1.) So Why is this error showing up and how can I fix it? Thanks
Solution 1:[1]
You are getting this error because 9,987,654,320 is too big to fit in a 32-bit integer.
Solution: Use long long instead. That is:
long long rev = 0;
long long temp = x;
Also, I suggest clearly specify the type of parameter x.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | a1knla |
