首页 > 其他 > 详细

[LeetCode]-009-Palindrome_Number

时间:2016-04-15 19:59:24      阅读:240      评论:0      收藏:0      [点我收藏+]

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

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、负数可以是回文的吗 负数不是回文整数
2、如果你想把整形转换成字符串来处理,注意空间限制
3、你也可以反转整数,但是可能出现溢出的情况

Test  cases:

-2147483648
=>false
-1
=>false
212
=>true
3
=>true

 1 public class Solution{
 2     public boolean isPalindrome(int x) {
 3         if(x<0)
 4             return false;
 5         if(x>=0 && x<=9)
 6             return true;
 7         int len = (x + "").length();
 8         int[] arr = new int[len];
 9         int index = 0;
10         while(x>0){
11             arr[index++] = x%10;
12             x = x/10;
13         }
14         System.out.println(Arrays.toString(arr));
15         int middle = (len+1)/2;
16         boolean flag = true;
17         for(index=0; index<middle; index++){
18             if(arr[index] != arr[len-1-index]){
19                 flag = false;
20             }
21         }
22         return flag;
23     }
24     
25     public static void main(String[] args){
26         int param = 5486;
27         if(args.length!=0)
28             param = Integer.valueOf(args[0]);
29         Solution solution = new Solution();
30         boolean res = solution.isPalindrome(param);
31         System.out.println(res);
32     }
33 }

 

[LeetCode]-009-Palindrome_Number

原文:http://www.cnblogs.com/lianliang/p/5396311.html

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