码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】9. Palindrome Number

时间:2016-09-10 11:37:32      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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;
    }
};

 

【LeetCode】9. Palindrome Number

标签:

原文地址:http://www.cnblogs.com/Doctengineer/p/5858965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!