Leetcode: Palindrome Numbers

本文探讨了一种高效判断整数是否为回文数的方法,通过两端对比的方式,并解决了中间含有0的问题,提供了完整的Java代码实现。
Determine whether an integer is a palindrome. Do this without extra space.

尝试用两头分别比较的方法,结果发现无法解决1000021这种问题

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if(x<0) return false;
 4         int lastbit=x%10;
 5         int firstbit;
 6         int num=x;
 7         int bits=0;
 8         while(num/10!=0){
 9             num=num/10;
10             bits++;
11         }
12         firstbit=num;
13         if(firstbit!=lastbit) return false;
14         else{
15             x=x-firstbit*((int)(Math.pow(10,bits)));
16             x=x/10;
17             if(x==0) return true;
18             else return isPalindrome(x);
19         }
20     }
21 }

查看了论坛的解答,看到一个很好的solution, 它怎么想到13行的 div/=100的,给跪了,这样刚好解决了中间有0的问题,比如1021会被判定为false, 而121会被判定为true。 解答详见:http://leetcode.com/2012/01/palindrome-number.html

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0) return false;
 4         int div = 1;
 5         while (x / div >= 10) {
 6             div *= 10;
 7         }        
 8         while (x != 0) {
 9             int l = x / div;
10             int r = x % 10;
11             if (l != r) return false;
12             x = (x % div) / 10;
13             div /= 100;
14         }
15         return true;
16     }
17 }

转载于:https://www.cnblogs.com/EdwardLiu/p/3710668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值