LeetCode 9:Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

又是回文,之前有一道题是最长子串,这里是整型数据

比较简单,这里直接转换成字符串,左右两个指针一直往中间靠拢,最终left和right要么重合(单数个数字),要么相邻(双数个数字),如果是回文,left和right位置字符肯定相同;反之不同

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/26 12:31
*/
class Solution {
public boolean isPalindrome(int x) {
String s = Integer.toString(x);
int left = 0;
int right = s.length() - 1;
while (left < s.length() - 1 && right > 0 && left <= right && s.charAt(left) == s.charAt(right)) {
left++;
right--;
}

return s.charAt(left) == s.charAt(right);
}
}

注意left和right的范围要判断一下,否则会越界,比如只有一个数字的时候

由于回文颠倒过来值不变,因此可以计算反过来的值,和原来的值是否一致,返回

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/26 12:31
*/
class Solution {
public boolean isPalindrome(int x) {
int a = 0;
int y = x;
// 123 = (1 * 10 + 2) * 10 + 3
// 3 = 123 % 10
// 32 = 3 * 10 + 12 % 10
// 321 = 32 * 10 + 1 % 10
while (y > 0) {
a = a * 10 + y % 10;
y /= 10;
}

return x == y;
}
}

发表评论