判断回文数
package Algorithms; /** * @author : zhang * @version : 1.0 * @date : Create in 2021/7/28 * @description : */ public class HuiWen { public static void main(String[] args) { int x = 100001; boolean palindrome = isPalindrome_2(x); System.out.println(palindrome); } //解法1,转化为字符串,反转后和原字符串进行比较 public static boolean isPalindrome_1(int x) { String reversedStr = (new StringBuilder(x + "").reverse().toString()); return (x + "").equals(reversedStr); } //解法2,数字反转后和原数字进行比较 public static boolean isPalindrome_2(int x) { if (x<0) return false; int reverseNumber = 0; int num = x; while (num!=0){ reverseNumber = reverseNumber*10 +num %10; num/=10; } return reverseNumber == x; } //解法3,取出后半数,和前半数进行比较 public static boolean isPalindrome_3(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) return false; int revertedNumber = 0; while (x > revertedNumber) { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } return x == revertedNumber || x == revertedNumber / 10; } }