LeetCode--No.009 Palindrome Number

9. Palindrome Number

  • Total Accepted: 136330
  • Total Submissions: 418995
  • Difficulty: Easy

  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.

 

  思路:

  本题解题很简单,首先判断负数和0,然后我们计算得到最大基数,如果x为一个两位数,则基数base=100,三位数则为1000等,然后我们每次分别取这个数的最高位和最低位进行比较,如果不相等,则直接返回false,相等则去掉最左边和最右边的数后进行下一轮比较。代码如下:

 1 public boolean isPalindrome(int x) {
 2     if(x < 0){
 3         return false ;
 4     }
 5     if(x == 0 ){
 6         return true ;
 7     }
 8     
 9     int base = 1 ;
10     while(x/base >= 10){
11         base *= 10 ;
12     }
13     
14     while(x != 0){
15         int leftDigit = x/base ;
16         int rightDigit = x%10 ;
17         if(leftDigit != rightDigit){
18             return false ;
19         }
20         x = x%base/10 ;
21         base /= 100 ;
22     }        
23     return true ;      
24 }

 

转载于:https://www.cnblogs.com/mukekeheart/p/5708690.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值