Leetcode 第8题 判断一个整数是否为回文串

来源:互联网 发布:淘宝客退款还算佣金吗 编辑:程序博客网 时间:2024/06/05 03:02

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

click to show spoilers.

Subscribe to see which companies asked this question


思路很简单,直接将原回文串导过来,判断是否相等。(负数不知道怎么处理,但是按照结果来看,负数直接判错)

同时,考虑到倒过来可能造成超出整数范围,因此中间变量用long。

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


当然,也可以先进行循环得到长度,然后每次取最后一位和最前一位比较。代码就不写了。

http://www.cnblogs.com/remlostime/archive/2012/11/13/2767676.html

0 0
原创粉丝点击