本題還是反轉一個整數的題目,首先確定負數不是palindrome,題目的提示裏有 You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 我們可以這樣來解決,用result來代表反轉的結果,當正確時result不會大於原數字,只需判斷result是否大於原數字即可,無需等到result溢出了才返回false。代碼如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x <0)
return false;
int num = x,result=0;
while(num > 0)
{
if(result < x)
{
result = result*10+ num %10;
num /= 10;
}
else
return false;
}
if(result == x)
return true;
else
return false;
}
};