9. Palindrome Number [E] palindrome

topic

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


C ++ ideas

C ++ knowledge

Palindrome determination method:

  1. The numbers in reverse order, and compared with the original figures to see if the same
  2. The second half to reverse the numbers, comparing it with some numbers in the first half, to see if the same.

    Ideas 1

    All the figures reversed, compared with the original number.
bool isPalindrome(int x){
  if(x < 0) //所有的负数都不是回文数
    return false;
  long a = 0;
  int b = x;
  while(b!=0){
    a = a * 10 + b % 10;
    b /= 10;
  }
  if(a == x)
    return true;
  else
    return false;
}

Ideas 2

Reversal half figures, so the question is, how to judge has been reversed to the digital half of it? Due to the original figure is divided by 10, for digital reversal is multiplied by 10, if the original figure is less than the number of newly generated, then the show has reached half the number. Further parity also points discussion, assume that a newly generated number, b is the original number,

  • If an odd number, it is determined that a / 10 == b
  • If it is even, directly determines a == b
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 ideas

Ideas 1

Fragment into a string of processing

def isPalindrome(self, x):
  b = str(x)
  converNum = b[::-1]
  return converNum == b

Ideas 2

1 with C ++ ideas

def isPalindrome(self, x):
  if(x < 0):
    return False
  reverseNum = 0
  m = x
  while m > 0:
    reverseNum = reverseNum * 10 + m %10
    m = m//10
  return reverseNum == x

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993443.html