Palindrome Number

来源:互联网 发布:数据分析是怎么接兼职 编辑:程序博客网 时间:2024/04/30 20:09

1、一提到数字的时候就要想到正负的判断;
2、巧妙的利用/,%来取数字的每位数;
题目:
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.
判断一个数字是不是回文;
思路:
想办法取出首位两个字符,判断他们两个是否相等;
代码:

class Solution {public:    bool isPalindrome(int x) {        if(x<0) return false;        int len=1;        while(x/len>=10)        {            len*=10;        }        while(x!=0)        {            int left=x/len;            int right=x%10;            if(left!=right) return false;            x=(x%len)/10;            len/=100;        }        return true;    }};
0 0
原创粉丝点击