Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
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?
There is a more generic way of solving this problem.
class Solution { public boolean isPalindrome(int x) { }}
实例类:
class Solution { public static boolean isPalindrome(int x) { int res = 0; int result = x; if(x<0){ return false; } while (result != 0){ res = res *10 + result %10; result = result/10; } return x == res; }}
测试类:
import java.util.Scanner;public class test extends Solution{ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入内容:"); int in = input.nextInt(); boolean out = isPalindrome(in); System.out.println("输出为:"+out); }}
结果:
请输入内容:123321输出为:true