5.Palindrome Number

Description:

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

Difficulty: Easy

 

palindrome的意思是回数,即数字顺序颠倒后仍和原数字相等的数字。

引用百度百科的定义:

  设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。

 

0-9都是回文数

解题思路:

  把数字颠倒后与原数字比较是否仍相等

  颠倒数字的处理与之前题目的手法一样

public:
bool isPalindrome(int x) {
    int temp=0;
    int x1=x;
    if(x<0) return false;
    if(x==0) return true;
    while(x){
      temp=temp*10+x1%10;
      x1 = x1 / 10;
      }
    if(temp==x)
      return true;
    else
      return false;
  }

 

我在solution里发现一个更加快捷的解答,它并不需要全部颠倒,只需要颠倒至数字的中间位置即通过比较大小来实现算饭,摘录如下

class Solution {

  public: bool isPalindrome(int x){

    if(x<0|| (x!=0 &&x%10==0)) return false;

    int sum=0;

    while(x>sum) {

      sum = sum*10+x%10;

      x = x/10;

    }

    return (x==sum)||(x==sum/10);

  }

};

posted @ 2017-03-21 12:11  legooooo  阅读(318)  评论(0编辑  收藏  举报