Link: leetcode-cn.com/problems/pa…
1. Title:
Checks whether an integer is a palindrome. Palindromes are integers that read in positive (left to right) and backward (right to left) order.
Example 1
Input: 121 Output: true
Example 2
Input: -121 Output: false Description: Read from left to right. The value is -121. Read from right to left, 121-. So it’s not a palindrome number.
Example 3
Input: 10 Output: false Description: Read from right to left. The value is 01. So it’s not a palindrome number.
Can you solve this problem by not converting integers to strings?
2, analysis,
An integer cannot be converted to a string.
As a palindrome is a symmetrical number, it is the same when read from left to right. Therefore, it is possible to flip the digits of the palindrome and compare whether the flipped digits are the same as the original digits. If the same is a palindrome, the different is not a palindrome.
2.1. Exclude negative numbers
Since the object being processed is an integer, a negative number cannot be a palindrome
2.2. How do I flip numbers
To obtain the various bits of an integer, use the exact division and mod method, for example, the integer 121
- Mod: 121%10 = 1, divisible: 121/10 = 12
- Mod: 12%10 = 2, divisible: 12/10 = 1
- Mod: 1%10 = 1, divisible: 1/10 = 0
As shown by the red numbers above, the resulting 1, 2, and 1 are the digits from right to left
2.3. Calculate the flipped figures according to each
You need to know how many bits there are to figure it out. Or you could do it exactly divisible.
2.4. Steps to solve the problem
At this point, our problem-solving ideas come out, summarized as follows:
1. Exclude negative numbers 2. Calculate how many digits there are 3
3, code,
public class N9 {
public static void main(String[] args) {
int x = 12321;
System.out.println(new N9().isPalindrome(x));
}
public boolean isPalindrome(int x) {
if(x < 0){
return false; } int num1 = x; int num2 = x; Int size = 1;while(num1 / 10 ! = 0){ size *= 10; num1 = num1 / 10; Int reverse = 0; int reverse = 0;while(num2 ! = 0){ int right = num2 % 10; reverse += right * size; num2 = num2 / 10; size = size / 10; } // Is the final comparison equalreturnx == reverse; }}Copy the code