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

Palindrome Number

时间:2015-04-12 14:41:36      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Palindrome Number

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4419442.html

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