9. Palindrome Number[E]回文数

题目


Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example1:
  Input:121
  Output:true
Example2:
  Input:-121
  Output:flase
  Explanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example3:
  Input:10
  Output:flase
  Explanation:Reads 01 from right to left. Therefore it is not a palindrome.

C++思路


思路1:全部逆序

将数字全部逆转,与原数字比较。

思路2:逆转一半的数字

如何判断已经逆转到数字的一半呢?由于对于原数字是除以10,对于逆转的数字是乘以10,如果原来的数字已经小于新生成的数字,那么就表明已经到达数字的一半。此外还要分奇偶讨论,假设a是新生成的数字,b是原数字,则

  • 如果是奇数,则判断a/10 == b
  • 如果是偶数,直接判断 a == b

思路3:字符串分片处理(python)

Tips


回文判断方法

  1. 将数字逆序,并与原数字比较,查看是否一致
  2. 将数字后半部分逆转,将其与前半部分数字比较,查看是否一致。

c++


  • 思路1
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)   //所有的负数都不是回文数
            return false;
        int a = x;
        long b = 0;
        while(a!=0){
            b=b*10 + a%10;
            a /= 10;
        }
        
        if(b == x)
            return true;
        else
            return false;
    }
};
  • 思路2
class Solution {
public:
   bool isPalindrome(int x){
    //特殊情况
    if(x < 0 || (x % 10 ==0 && x!=0)){
      return 0
    }
    long a = 0;
    int b = x;
    while(a < b){
      a = a * 10 + b % 10;
      b /= 10;
    }
    return b = =a || b ==a/10;
  }
};

Python


  • 思路3
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        b = str(x)
        converNum = b[::-1]
        return converNum == b
  • 思路1
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
            return False
        a = 0
        b = x
        while b>0:
            a =a*10+b%10
            b = b/10
        return a==x

转载于:https://www.cnblogs.com/Jessey-Ge/p/10993443.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值