标签:
Determine whether an integer is a palindrome. Do this without extra space.
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.
注意: negetive integers are not palindromes
思路: 将数字reverse 如果 reverse之后等于原数字则为palindrome 在reverse的过程中注意overflow的情况。
1 public class Solution { 2 public boolean isPalindrome(int x) { 3 if (x < 0) { 4 return false; 5 } 6 return x == reverse(x); 7 } 8 9 int reverse(int n) { 10 int result = 0; 11 while (n != 0) { 12 int temp = result * 10 + n % 10; 13 if (temp / 10 != result) { 14 result = 0; 15 break; 16 } 17 n = n / 10; 18 result = temp; 19 } 20 return result; 21 } 22 23 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5486358.html