Palindrome Number

来源:互联网 发布:php代码批量替换工具 编辑:程序博客网 时间:2024/06/13 22:39

Determine whether an integer is a palindrome. Do this without extra space.
思路:

  1. 逆转该数字,看逆转前后是否相等。
  2. 确定该数的数量级,一次由两边想中间比较对称的两个数是否相等。

需要注意的是负数是palindrome。

class Solution {public:    bool isPalindrome(int x) {        if(x < 0)            return false;        else if(x >=0 && x < 10)            return true;        else{            long ret = 0, tmp = x;            while(tmp){                ret = ret * 10 + tmp % 10;                tmp = tmp / 10;            }            return int(ret) == x;        }    }};
class Solution {public:    bool isPalindrome(int x) {        if(x < 0)            return false;        else if(x >=0 && x < 10)            return true;        else{            int len = 1;//数量级            while(x/len >= 10)                len *= 10;            while(x){                int r = x % 10;                int l = x / len;                if(r != l)                    return false;                else{                    x = (x % len) / 10;                    len /= 100;                }            }            return true;        }    }};
0 0
原创粉丝点击