您的位置:首页 > 其它

Palindrome Number

2015-09-10 12:48 253 查看
题目

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.

一种方法可以避免造成溢出,就是直接安装PalidromeString的方法,就直接判断第一个和最后一个,循环往复。这样就不会对数字进行修改,而只是判断而已。

public boolean isPalindrome(int x) {
//negative numbers are not palindrome
if (x < 0)
return false;

// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div *= 10;
}

while (x != 0) {
int left = x / div;
int right = x % 10;

if (left != right)
return false;

x = (x % div) / 10;
div /= 100;
}

return true;
}


Reference:
http://www.programcreek.com/2013/02/leetcode-palindrome-number-java/ http://www.cnblogs.com/springfor/p/3889214.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: