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