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

来源:互联网 发布:16奥运会中国男篮数据 编辑:程序博客网 时间:2024/06/06 19:03

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;    }}
原创粉丝点击