130.Palindrome Number(回文数)

题目:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

确定整数是否是回文。 当它向前读取向后时,整数是回文。

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

解答:

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

详解:

1.x不能为负数 或者 x的最高位不为0即x的最低位不为0(x%10)当然x可以为0

2.取x的低位半段翻转与高位半段比较,若x的长度为偶数,反转后高位半段(x)与低位半段(revertNum)应相等;若x的长度为奇数,反转后最中间那一位在revertNum的个位,      revertNum/10后与x相等

3.长度为偶数的例子:1221,高位半段12,低位半段21,低位半段反转后为12,与高位半段相等

4.长度为奇数的例子:121,高位半段1,低位半段21,低位半段反转后为12,除以10后为1,与高位半段相等

posted @ 2018-08-31 16:11  chan_ai_chao  阅读(158)  评论(0编辑  收藏  举报