Palindrome Number

来源:互联网 发布:百度飞豆软件 编辑:程序博客网 时间:2024/05/16 11:14

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.

题目:判断一个整数是不是回文数。

分析:方法一:每次取整数的正数第k个和倒数第k个,看是否相等,然后依次向中间逼近。如果某位上不相等,则不是回文数。

代码:

class Solution {public:    bool isPalindrome(int x) {        if(x<0) return false;//<0的不是回文数        if(x<10) return true;//只有一位的是回文数        long long gethead=1;//用于取从头的第k位        while(gethead<=x){            gethead*=10;        }        gethead/=10;        long long getend=10;        int t=x;        while(gethead>=getend){//如果两者没有到中间,一直循环            int headi=t/gethead;            int endi=(t%getend)/(getend/10);            if(headi!=endi) return false;            t=t%gethead;            gethead/=10;            getend*=10;        }        return true;    }};
方法二:reverse interge的方法,reverse之后两个值相等,则说明是回文数。注意不是回文数的可能超出整型范围的问题。
代码:

class Solution {public:    bool isPalindrome(int x) {        if(x<0) return false;        long long num=0;        int t=x;        while(t>0){            num=num*10+t%10;            t=t/10;        }        return (int)num==x ;    }};

0 0
原创粉丝点击