EX:
Input: 121
Output: trueInput: -121 Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
想法:
這題判斷方式主要就是將給定的整數翻轉過來看看是否和原來的數一樣即可判斷,翻轉的方式可以參考 7. Reverse Integer,比較需要注意的地方跟 7. Reverse Integer 一樣需要注意 overflow 的情況,發生 overflow 表示該數不可能是回文。
Complexity: O(n) time, O(1) space.完整程式碼:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x !=0)) { return false; }
int reversed = 0;
int x_ori = x;
while (x > 0) {
// if reversed is overflow, then x is impossible to be palindrome
if (reversed > INT_MAX / 10) { return false; }
reversed = reversed * 10 + x % 10;
x = x / 10;
}
return reversed == x_ori;
}
};
沒有留言:
張貼留言