Question
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: true
Example 2:
Input: -121 Output: false 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 Output: false 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?
My Answer
实现方式有点 low,直接反过来,然后比较两个数字是否相对。还可以优化
class Solution {
public boolean isPalindrome(int x) {
if(x < 0) {
return false;
}
int v = x, y = 0;
while(x > 0) {
y = y * 10 + x % 10;
x = x /10;
}
return v == y;
}
}
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏