【LeetCode】9. Palindrome Number

题目:

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

简单题。看到两个比较好的解法,一个是把数字转化为字符串,然后首尾对比,往中间靠。另一种是数字分别从两头求和(保留位数:*10 + 余数),如果相同则true。这样遍历只要是O(n/2)就可以。

class Solution {
public:
    bool isPalindrome(int x) {
       if (x < 0) return false;
       if ( x < 10 && x >= 0 ) return true;
       
       int res = 0;

       int tmp = x;
       while (tmp > 0){
           res = res * 10 + tmp%10;
           tmp /= 10;
       }
       
       return res == x;
    }
};

 

posted on 2016-09-10 10:43  医生工程师  阅读(87)  评论(0编辑  收藏  举报

导航