9. Palindrome Number (JAVA)
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。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.
Follow up:
Coud you solve it without converting the integer to a string?
class Solution { public boolean isPalindrome(int x) { if(x<0) return false; int left; //the first bit of the inteter int right; //the last bit of the integer int divisor = 1; //divisor of each iteration int tmp = x; //determine the initial value of divisor while(x/divisor >= 10){ divisor *= 10; } //check palindrome while(x>0){ left = x/divisor; //divided by divisor to get the first bit right = x%10; //mod 10 to get the last bit if(left != right) return false; x = (x%divisor)/10; //mode divisor to remove the first bit, divided by 10 to remove the last bit divisor /= 100; } return true; } }
数字问题注意:
1. 负数
2. 变换后 以0开始 (本题中,如10101)这种情况,除以divisor = 0,mod 10 = 最后那位。
有多少个0,就得经过多少次循环,才能使得divisor的长度和被除数相等。在长度不等的时候,没次都循环末尾需为0,才能符合Palindrome的判断。所以该算法仍然可以验证有0开头的情况。

更多精彩