Q9:Palindrome Number

本文介绍了一种高效判断整数是否为回文数的方法,通过反转数字的一半来进行比较,避免了完全反转导致的溢出问题,并给出了具体的实现代码。

9. Palindrome Number

官方的链接:9. Palindrome Number

Description :

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. 特殊值问题:大于0的数字,且个位数是0,明显不是。小于0的负数,明显不是
  2. 数字是奇数位:反转的数字/10=前半部分
  3. 数字是偶数位:反转的数字=前半部分
  4. 因此关键的判断条件就是:反转的数字 < 前半部分

回文数-维基百科
回文数-百度百科

其他的可以參考官网的讨论,自己总结并写代码

[github-here]

 

 1 public class Q9_PalindromeNumber {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0 || (x > 0 && x % 10 == 0)) {
 4             return false;
 5         }
 6         int revX = 0;
 7         while (revX < x) {
 8             revX = revX * 10 + x % 10;
 9             x /= 10;
10         }
11         return (revX == x || revX / 10 == x);
12     }
13 }

 

转载于:https://www.cnblogs.com/wpbxin/p/8660596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值