問題
判斷一個整數是否是回文數。回文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。
示例 1:
輸入: 121 輸出: true
示例 2:
輸入: -121 輸出: false 解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個回文數。
示例 3:
輸入: 10 輸出: false 解釋: 從右向左讀, 為 01 。
因此它不是一個回文數。
思路
思路很簡單明了嘛,回文數,顛倒以后還一樣的數字,那你就顛倒一下嘛。不過有幾種情況可以直接判定。
- 負數。因為符號顛倒過來以后負號在后面,那肯定就不是個數字嘛,直接排除。
- 個位數是0的數字。這肯定也不行嘛,因為顛倒以后0在最高位,你見過最高位是0的整數嗎?沒有,所以排除掉。至于說顛倒整數嘛,可以參考我前面寫過的顛倒整數。
使用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(Solution.isPalindrome(10));
}
}
輸出
這不是回文數
false
Process finished with exit code 0
實現
package com.company;
public class Solution {
/**
* 判斷一個數是不是回文數
* @param inputInt
* @return
*/
static public boolean isPalindrome(int inputInt) {
if (inputInt < 0 || (inputInt > 0 && inputInt % 10 == 0)) {
System.out.println("這不是回文數");
return false;
}
if (inputInt == 0)
return true;
int reveredInt = Solution.reverseInt(inputInt);
if (reveredInt == 0)return false;
else {
if (inputInt - reveredInt == 0)return true;
else return false;
}
}
static private int reverseInt(int inputInt) {
if (inputInt > Integer.MAX_VALUE || inputInt < Integer.MIN_VALUE) {
System.out.println("輸入數字越界");
return 0;
}
int pseudoMax = Integer.MAX_VALUE / 10;
int maxLowestNumber = Integer.MAX_VALUE % 10;
int minLowestNumber = Integer.MIN_VALUE % 10;
int inputCopy = inputInt;
int result = 0;
while (inputCopy != 0) {
int singleNumber = inputCopy % 10;
inputCopy /= 10;
if (Math.abs(result) > pseudoMax) {
return 0;
} else if (Math.abs(result) == pseudoMax) {
result *= 10;
if (inputInt < 0) {
if (singleNumber < minLowestNumber)return 0;
else result += singleNumber;
} else {
if (singleNumber > maxLowestNumber)return 0;
else result += singleNumber;
}
} else {
result = result * 10 + singleNumber;
}
}
return result;
}
}