LeetCode刷题 [9] 回文数
思路:逆序这个整数,然后和该整数比较
解法2: 使用StringBuilder的reverse方法逆序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package leetcode1_10;
public class LeetCode9_2 { public boolean isPalindrome(int x) { String xStr = String.valueOf(x); String reverseStr = new StringBuilder(String.valueOf(x)).reverse().toString(); return xStr.equals(reverseStr); }
public static void main(String[] args) { int[] testArr = {123, 121, 111, 1000, 12321, 2332}; LeetCode9_2 leetCode9_2=new LeetCode9_2(); for (int i = 0; i < testArr.length; i++) { System.out.println(testArr[i]+" 是回文数:"+leetCode9_2.isPalindrome(testArr[i])); }
} }
|
优点:代码量少
解法3: 通过数学运算逆序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution {
public boolean isPalindrome(int x) { if (x < 0 && (x % 10 == 0)) { return false; } int reverse = getReverse(x); return reverse == x; }
private int getReverse(int positiveInteger) { int reverseInteger = 0; while (positiveInteger > 0) { reverseInteger = reverseInteger * 10 + positiveInteger % 10; positiveInteger = positiveInteger / 10; } return reverseInteger; } }
|