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

Palindrome Number

时间:2015-05-04 21:35:51      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/palindrome-number/

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 static boolean isPalindrome(int x) {
 3     if(x<0){return false;}
 4         int len=0;
 5         String maxint=""+Integer.MAX_VALUE;
 6         int maxlen=maxint.length();
 7         if(x>=Math.pow(10,maxlen-1)||x<=-Math.pow(10, maxlen-1)){len=maxlen;}
 8         else{while((x/(int)Math.pow(10,++len))!=0);}
 9         for(int i=1;i<=len/2;i++){
10             int a=(int) (x%(Math.pow(10, i))/(Math.pow(10, i-1)));
11             int b=(int) (x%(Math.pow(10, len-i+1))/(Math.pow(10, len-i)));
12             if(a!=b){return false;}
13         }
14         return true;
15     }
16     public static void main(String[]args){
17     System.out.println(isPalindrome(-2147483648));
18     }
19 }

 

Palindrome Number

标签:

原文地址:http://www.cnblogs.com/qq1029579233/p/4477115.html

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