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?
如果可以用string,那么就可以
public boolean isPalindrome(int x) { String input = String.valueOf(x); return Objects.equals(input, new StringBuilder(input).reverse().toString()); }
笨方法1:
Reverse integer 然后和原数字对比,如果对就是true。
class Solution { public boolean isPalindrome(int x) { boolean a = false; int res=0; int med = x; if(x<0||x%10==0){ a = false; } while(med>0){ res = res*10+ med%10; med/=10; } if(x==res) a=true; return a; } }
方法2:
只用取出后一半的数字,和前一半的数字进行对比,如果相等则返回true
class Solution { public boolean isPalindrome(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) return false; int revertNum = 0; while (x > revertNum) { revertNum = revertNum * 10 + x % 10; x /= 10; } return x == revertNum || x == revertNum / 10; } }
这种方法比上面的理论上快一倍。