首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >No.009 Palindrome Number

No.009 Palindrome Number

作者头像
mukekeheart
发布2018-02-27 12:02:19
4110
发布2018-02-27 12:02:19
举报

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 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-07-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 9. Palindrome Number
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档