Palindrome Number

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

Analyse:判断一个整数是否是回文数。注意负数都不是回文数。

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x < 0) return false;
 5         string s;
 6         while(x){
 7             char temp = x % 10 + '0';
 8             s += temp;
 9             x /= 10;
10         }
11         bool result = true;
12         for(int i = 0; i < s.length() / 2; i++){
13             if(s[i] != s[s.length() - 1 - i]) return false;
14         }
15         return true;
16     }
17 };

 或者:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x < 0) return false;
 5         else if(x < 10) return true;
 6         else{
 7             int div = 1000000000;
 8             while(x / div == 0) div /= 10;
 9             bool result = true;
10             while(x){
11                 int left = x / div;
12                 int right = x % 10;
13                 if(left != right){
14                     result = false;
15                     break;
16                 }
17                 x = (x- left * div) / 10;
18                 div /= 100;
19             }
20             return result;
21         }
22     }
23 };
View Code

 

posted @ 2015-04-12 14:00  amazingzoe  阅读(129)  评论(0编辑  收藏  举报