Math
Q****9. Palindrome Number
Given an integer x
, return true
if x is a palindrome, and false otherwise.
Example 1:
vbnet
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
vbnet
Input: x = -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:
vbnet
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
解法及注释:
sql
class Solution { public boolean isPalindrome(int x) { //pre-check if(x < 0 || x > Math.pow(2,31)-1 || (x != 0 && x %10 == 0 )) { return false; } if(x < 10) { return true; } return useString(x); //return useMath(x); } private boolean useString(int x) { String s = String.valueOf(x); int n = s.length(); for(int i = 0; i < n/2; i++) { if(s.charAt(i) != s.charAt(n-i-1)) { return false; } } return true; } private boolean useMath(int x) { int rev = 0; while(x > rev) { rev = rev * 10 + x % 10; x /= 10; } return (x == rev || x == rev/10); }}