The title
Given an integer x, return true if x is a palindrome integer; Otherwise, return false.
Palindromes are integers that read in positive (left to right) and backward (right to left) order. For example, 121 is palindrome and 123 is not.
Example 1:
Input: x = 121 Output: trueCopy the code
Example 2:
Input: x = -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.Copy the code
Example 3:
Input: x = 10 Output: false Description: Read from right to left, 01. So it's not a palindrome number.Copy the code
Example 4:
Input: x = -101 Output: falseCopy the code
Tip:
-231 <= x <= 231 - 1
Copy the code
Source: LeetCode link: leetcode-cn.com/problems/pa… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Concluding thinking
- Turn the string
Convert an integer to a string, and then verify that the numbers are equal from both sides to the middle.
- Digit reversal comparison
Invert the integer and the resulting number is denoted as rever, or palindrome if rever is equal to the original number. However, because of the int type, an overflow can occur during inversion, so you only need to reverse half of the number to see if it equals the other half. Another advantage of this approach is that the computation is cut in half. The process of reversal is to take out the ones place of x, and then rever=rever*10+ ones, until it ends halfway through the reversal. So when is it half reversed? That is, when x < rever, it has reversed half of the number and should stop. Because the number of odd and even numbers are different, there are two cases, as follows:
code
- Turn the string
public boolean isPalindrome(int x) { char[] s = String.valueOf(x).toCharArray(); int lenth = s.length; int end = lenth - 1; for (int i = 0; i < lenth/2; i++, end--) { if (s[i] ! = s[end]) { return false; } } return true; }Copy the code
- Digit reversal comparison
Public Boolean isPalindrome (int x) {/ / has special processing of negative Numbers and bits of 0 if (x < 0 | | (10 x % = = 0 x &&! = 0)) { return false; } int rever = 0; while (x > rever) { rever = rever * 10 + x % 10; x /= 10; } return x == rever / 10 || x == rever; }Copy the code
The test case
public class Solution_Test_9 { Solution_9 solution_9 = new Solution_9(); @Test public void test1() { int x = 121; boolean ans = solution_9.isPalindrome(x); assertEquals(ans, true); } @Test public void test2() { int x = -121; boolean ans = solution_9.isPalindrome(x); assertEquals(ans, false); } @Test public void test3() { int x = 10; boolean ans = solution_9.isPalindrome(x); assertEquals(ans, false); } @Test public void test4() { int x = -101; boolean ans = solution_9.isPalindrome(x); assertEquals(ans, false); }}Copy the code