leetcode:Palindrome Number

来源:互联网 发布:top域名怎么备案 编辑:程序博客网 时间:2024/06/06 08:49

晚上做了两道回文的题目,一道是回文数,一道是回文字符串,自己写的代码考虑的不清楚,出现了许多逻辑错误,下面列了三种比较简洁的代码,供后面学习。

1.第一种

class Solution {public:    bool isPalindrome(int x) {        if(x<0)  return false;        if(x==0)  return true;                int base=1;        while((x/base)>=10)        {            base*=10;        }                while(x)        {            int left=x/base;            int right=x%10;                        if(left!=right)  return false;                        x-=left*base;       //这一步和后面的一步是为了同时去丢当前数字的最左和最右两位数,这一步很重要,少了后面许多复杂的判断            x=x/10;            base=base/100;        }        return true;    }};

2. 第二种,其实和第一种思想一样,只不过其去除最左和最右位的表达式很简洁,赞一个。

class Solution {public:    bool isPalindrome(int x) {        if(x<0)  return false;        if(x==0)  return true;                int base=1;        while((x/base)>=10)        {            base*=10;        }                while(x)        {            int left=x/base;            int right=x%10;                        if(left!=right)  return false;                        x=(x%base)/10;    //同时去掉最左和最右两个数            base=base/100;         }        return true;    }};
3. 第三种,使用了翻转数字的方法

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


0 0
原创粉丝点击