首页 > 其他 > 详细

LeetCode(9)--Palindrome Number

时间:2015-05-09 18:58:47      阅读:154      评论:0      收藏:0      [点我收藏+]

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

 

思想: 先计算出这个整数的逆序数,然后比较它和原来的数每位是否都相同即可。另外要注意负数没有回文数,还应该考虑overflow一定不是回文数。

 

AC代码:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x<0)
 5             return false;
 6         int y=0,tmp=x;
 7         while(tmp!=0){
 8             y=10*y+tmp%10;
 9             tmp=tmp/10;
10         }
11         while(x!=0 || y!=0){
12             if(x%10!=y%10)
13                 return false;
14             x=x/10;
15             y=y/10;
16         }
17         return true;
18     }
19 };

 

advance:

其实可以不求出逆序数,直接比较,见讨论板的代码:

 1 class Solution {
 2 public:
 3     bool isPalindrome(long long x) {
 4         if (x < 0) return false;
 5         long long d = 10, e = 10;
 6         while (x / d) d *= 10;
 7         while (d > e)
 8         {
 9             if ((x % d) / (d / 10) != (x % e) / (e / 10))
10                 return false;
11             d /= 10;
12             e *= 10;
13         }
14         return true;
15     }
16 };

 

LeetCode(9)--Palindrome Number

原文:http://www.cnblogs.com/aezero/p/4490722.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!