Easy 3 Palindrome Number(9)

来源:互联网 发布:法医秦明 知乎 编辑:程序博客网 时间:2024/05/21 18:35

Description
Determine whether an integer is a palindrome. Do this without extra space.

Solution
判断一个整型数是否为回文。如果将integer全翻转,可能会导致整数溢出。但这并不影响判断,因为若是回文,则翻转必不会溢出。

class Solution {public:    bool isPalindrome(int x) {        int res=0;        int xx=x;        while(x){        res=res*10+x%10;        x/=10;        }        return ((res==xx)&&(res>=0));    }};

参考其他提交代码:可以采用半翻转形式,既避免溢出,有可节省计算量

class Solution {public:    bool isPalindrome(int x) {        if(x<0||(x!=0&&x%10==0)) return false;        int res=0;        while(x>res){        res=res*10+x%10;        x/=10;        }        return (res==x)||(res/10==x);    }
0 0
原创粉丝点击