Description
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 </br>
Output: true </br>
Example 2:
Input: -121 </br>
Output: false </br>
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10 </br>
Output: false </br>
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
AC代碼
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int y = 0, z = x;
short int n=0;
while(z != 0) {
n = z % 10;
// 這一步是因為要確保 y*10 +n < INT_MAX
if(y > ((INT_MAX - n)/10)) return false;
y = y*10 + n;
z = z/10;
}
return (x==y);
}
// 這個函數(shù)僅僅是用來測試方便巩踏,提交的時候也可以不加
void judgeResult(int x) {
if(isPalindrome(x)) {
cout << x << " is palindrome" <<endl;
} else {
cout << x << " is not palindrome" <<endl;
}
}
};
測試代碼
int main() {
Solution s;
s.judgeResult(-121);
s.judgeResult(121);
s.judgeResult(456);
s.judgeResult(567898765);
}
測試結(jié)果
-121 is not palindrome
121 is palindrome
456 is not palindrome
567898765 is palindrome
總結(jié)
前面有類似的題目,是判斷字符串是否是回文字符串,這道題的描述里面說了在解題時應(yīng)避免先轉(zhuǎn)換成字符串再做回文。以上的AC代碼實際上是利用了之前某一道題目里面的反轉(zhuǎn)字符串,然后判斷字符串反轉(zhuǎn)后是否還與本身相等。