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
posted @ 2019-06-09 14:34  风雪初晴,宜下江南  阅读(108)  评论(0编辑  收藏  举报