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: trueExample 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:
Could you solve it without converting the integer to a string?
回文数。
题意是判断一个数字是否是回文数。这个题跟第7题非常类似,有两种做法,一种跟第七题很类似,另一种是把 input 数字转换成字符串然后双指针逼近检测是否有不一样的字符。
无论什么做法,都有一些需要去掉的 corner case,首先负数一定不是回文数,能被 10 整除的数字也不是,其次回文数一定不会越界。类似第七题的代码如下,
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {number} x 3 * @return {boolean} 4 */ 5 var isPalindrome = function (x) { 6 // corner case 7 if (x < 0 || (x !== 0 && x % 10 === 0)) return false; 8 9 // normal case 10 let palindrome = x; 11 let reverse = 0; 12 while (x > 0) { 13 reverse = reverse * 10 + (x % 10); 14 x = ~~(x / 10); 15 } 16 return palindrome === reverse; 17 };
Java实现
1 class Solution { 2 public boolean isPalindrome(int x) { 3 // corner case 4 if (x < 0 || (x != 0 && x % 10 == 0)) return false; 5 6 // normal case 7 int palindrome = x; 8 int reverse = 0; 9 while (x > 0) { 10 reverse = reverse * 10 + x % 10; 11 x /= 10; 12 } 13 return palindrome == reverse; 14 } 15 }
two pointer 逼近,如果发现两边不一样即可return false;否则就return true。
时间O(logn)
空间O(1)
Java实现
1 class Solution { 2 public boolean isPalindrome(int x) { 3 String s = String.valueOf(x); 4 int left = 0; 5 int right = s.length() - 1; 6 // corner case 7 if (s.charAt(0) == '-') { 8 return false; 9 } 10 11 while (left < right) { 12 if (s.charAt(left) != s.charAt(right)) { 13 return false; 14 } else { 15 left++; 16 right--; 17 } 18 } 19 return true; 20 } 21 }