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

Palindrome Number

时间:2014-08-01 12:49:41      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   io   for   cti   

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

 

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(x < 0) return false;
 5         int len = 0;
 6         int xx = x;
 7         while(xx > 0){
 8             len ++;
 9             xx = xx / 10;
10         }
11         for(int i = 0; i < len / 2; i ++){
12             int a = (x / (int)Math.pow(10, i)) % 10;
13             int b = (x / (int)Math.pow(10, len - i - 1)) % 10;
14             if(a != b) return false;
15         }
16         return true;
17     }
18 }

 第三遍:

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if(x < 0) return false;
 4         int num = 0;
 5         while(x >= Math.pow(10, num)) num ++;
 6         for(int i = 0; i < num / 2; i ++){
 7             int aa = x / (int)(Math.pow(10, num - i - 1)) % 10;
 8             int bb = x / (int)(Math.pow(10, i)) % 10;
 9             if(aa != bb) return false;
10         }
11         return true;
12     }
13 }

 

Palindrome Number,布布扣,bubuko.com

Palindrome Number

标签:style   blog   http   color   strong   io   for   cti   

原文地址:http://www.cnblogs.com/reynold-lei/p/3884368.html

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