判斷一個整數是不是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是同樣的整數。spa
示例 1:code
輸入: 121
輸出: true
示例 2:blog
輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。所以它不是一個迴文數。
示例 3:ip
輸入: 10
輸出: false
解釋: 從右向左讀, 爲 01 。所以它不是一個迴文數。leetcode
解法一:將數字反轉後,直接比較兩個數字的大小io
package com.zx.leetcode.isPalindrome; /** * @Author JAY * @Date 2019/6/7 12:26 * @Description 判斷一個整數是不是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是同樣的整數。 **/ public class Solution { public static void main(String[] args) { System.out.println(isPalindrome(2147483647)); System.out.println(isPalindrome(121)); } public static boolean isPalindrome(int x) { //須要考慮數字反轉以後是否超過int的界限 if(x < 0){ return false; } int y = x; String num = String.valueOf(x); int length = num.length(); double convertNum = 0; for(int i = length - 1; i >= 0 ; i--){ int high = (int) (x / Math.pow(10,i)); convertNum = convertNum + high * Math.pow(10,length - i - 1); x = (int) (x - high * Math.pow(10,i)); } if (convertNum == y){ return true; } return false; } }
解法二:經過取整和取餘操做獲取整數中對應的數字進行比較。class
1 package com.zx.leetcode.isPalindrome; 2 3 /** 4 * @Author JAY 5 * @Date 2019/6/7 12:26 6 * @Description 判斷一個整數是不是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是同樣的整數。 7 **/ 8 public class SolutionV2 { 9 10 public static void main(String[] args) { 11 System.out.println(isPalindrome(2147483647)); 12 System.out.println(isPalindrome(121)); 13 } 14 15 public static boolean isPalindrome(int x) { 16 17 //須要考慮數字反轉以後是否超過int的界限 18 //邊界判斷 19 if (x < 0) { 20 return false; 21 } 22 int div = 1; 23 // 24 while (x / div >= 10) { 25 div *= 10; 26 } 27 while (x > 0) { 28 int left = x / div; 29 int right = x % 10; 30 if (left != right) { 31 return false; 32 } 33 x = (x % div) / 10; 34 div /= 100; 35 } 36 return true; 37 } 38 }