Topic
- Math
Description
https://leetcode.com/problems/palindrome-number/
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Example 4:
Input: x = -101
Output: false
Constraints:
- -2³¹ <= x <= 2³¹ - 1
Analysis
方法一:我写的,用一个10位整型数组存数位,然后首尾指针向中夹逼迭代数组元素过程中,判断所指元素的相等性,从而判断实参是否是回文数。
方法二:利用回文的轴对称性,也就是轴右半部分反转的数是否等于前半部分的数。
方法三:更方法二类似,一个数的如果是回文数,那么这数反转后,与原数相等。该方法并没有明显处理负数和溢出的情况的代码,是一个似非而是的方法。
Submission
public class PalindromeNumber {
// 方法一:我写的
public boolean isPalindrome1(int x) {
if (x < 0)
return false;
int[] digits = new int[10];
int leftIndex = 0, rightIndex = -1;
while (x > 0) {
digits[++rightIndex] = x % 10;
x /= 10;
}
while (leftIndex < rightIndex) {
if (digits[leftIndex++] != digits[rightIndex--])
return false;
}
return true;//
}
// 方法二:
public boolean isPalindrome2(int x) {
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int rev = 0;
while (x > rev) {
rev = rev * 10 + x % 10;
x = x / 10;
}
return (x == rev || x == rev / 10);
}
// 方法三:
public boolean isPalindrome3(int x) {
int palindromeX = 0;
int inputX = x;
while (x > 0) {
palindromeX = palindromeX * 10 + (x % 10);
x = x / 10;
}
return palindromeX == inputX;
}
}
Test
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeNumberTest {
@Test
public void test() {
PalindromeNumber obj = new PalindromeNumber();
assertTrue(obj.isPalindrome1(121));
assertTrue(obj.isPalindrome1(2147447412));
assertFalse(obj.isPalindrome1(-121));
assertFalse(obj.isPalindrome1(10));
assertFalse(obj.isPalindrome1(-101));
assertFalse(obj.isPalindrome1(Integer.MAX_VALUE));
assertTrue(obj.isPalindrome2(121));
assertTrue(obj.isPalindrome2(2147447412));
assertFalse(obj.isPalindrome2(-121));
assertFalse(obj.isPalindrome2(10));
assertFalse(obj.isPalindrome2(-101));
assertFalse(obj.isPalindrome2(Integer.MAX_VALUE));
assertTrue(obj.isPalindrome3(121));
assertTrue(obj.isPalindrome3(2147447412));
assertFalse(obj.isPalindrome3(-121));
assertFalse(obj.isPalindrome3(10));
assertFalse(obj.isPalindrome3(-101));
assertFalse(obj.isPalindrome3(Integer.MAX_VALUE));
}
}
670

被折叠的 条评论
为什么被折叠?



