LeetCode 9. Palindrome Number

来源:互联网 发布:四川联通大数据 编辑:程序博客网 时间:2024/06/03 07:14

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.

从左右两边向中间判断,出现不同就相等,就返回false。当相遇就返回true.

public class Solution {    public boolean isPalindrome(int x) {        if(x < 0) return false;        if(x == 0) return true;        int  leftOffset = 1000000000;        int rightOffset = 10;        while(x/leftOffset == 0) leftOffset = leftOffset/10;                while(x != 0){            int left = x/leftOffset;                int right = x%rightOffset;            if(left !=right) return false;<pre name="code" class="java">class Solution {public:    bool isPalindrome(int x) {        if(x<0|| (x!=0 &&x%10==0)) return false;        int sum=0;        while(x>sum)        {            sum = sum*10+x%10;            x = x/10;        }        return (x==sum)||(x==sum/10);    }};

x=x%leftOffset; x = x/10; leftOffset = leftOffset/100; } return true; }}


论坛上还用将int翻转然后比较相等的,为了防止溢出,只翻转一半,再比较点击打开链接。

class Solution {public:    bool isPalindrome(int x) {        if(x<0|| (x!=0 &&x%10==0)) return false;        int sum=0;        while(x>sum)        {            sum = sum*10+x%10;            x = x/10;        }        return (x==sum)||(x==sum/10);    }};


0 0
原创粉丝点击