您的位置:首页 > 编程语言 > Java开发

LeetCode-9.Palindrome Number(求回文数字)

2017-07-27 17:51 330 查看

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.


初步通过的代码:

public class Solution {
public boolean isPalindrome(int x) {
if(x<0){
return false;
}
int ori = x;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
int sum  = 0;
while(x!=0){
if(sum>max/10||sum<min/10){
return false;
}
sum =  sum*10+x%10;
x/=10;
}

if(sum == ori){
return true;
}else{
return false;
}
}
}


优化的代码:不需要考虑溢出

public class Solution {
public boolean isPalindrome(int x) {
if(x==0){
return true;
}
if(x<0||x%10==0){
return false;
}
int rightPart = 0;
while (x>rightPart){
rightPart = rightPart*10 +x%10;
x =  x/10;
}
if(rightPart==x || rightPart/10 ==x){
return true;
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode-java