一、題目名稱java
Palindrome Number(迴文數)ui
二、題目地址this
https://leetcode.com/problems/palindrome-numberspa
三、題目內容.net
英文:Determine whether an integer is a palindrome. Do this without extra space.code
中文:確認一個整數是不是迴文數blog
四、解題方法1leetcode
將數字翻轉後判斷與原數字是否相等,能夠參考LeetCode第7題(Reverse Integer)的解題思路。Java代碼以下:開發
/** * 功能說明:LeetCode 9 - Palindrome Number * 開發人員:Tsybius * 開發時間:2015年9月24日 */ public class Solution { /** * 判斷某數是否爲迴文數 * @param x 數字 * @return true:是,false:否 */ public boolean isPalindrome(int x) { //負數不能爲迴文數 if (x < 0) { return false; } //反轉數字觀察是否相等 if (x == reverse(x)) { return true; } else { return false; } } /** * 反轉數字 * @param x 被反轉數字 * @return 反轉後數字 */ public int reverse(int x) { long result = 0; while (x!=0) { result = result * 10 + x % 10; x /= 10; } return (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) ? 0 : (int)result; } }
五、解題方法2字符串
另外一個方法是將數字轉換爲字符串,再經過StringBuilder類反轉字符串,判斷兩字符串相等。Java代碼以下:
/** * 功能說明:LeetCode 9 - Palindrome Number * 開發人員:Tsybius * 開發時間:2015年9月24日 */ public class Solution { /** * 判斷某數是否爲迴文數 * @param x 數字 * @return true:是,false:否 */ public boolean isPalindrome(int x) { if (x < 0) return false; if (x < 10) return true; String str1 = String.valueOf(x); String str2 = (new StringBuilder(str1)).reverse().toString(); if (str1.equals(str2)) { return true; } else { return false; } } }
六、解題方法3
還有一個方法,就是直接轉換爲字符串,而後再分別對字符串對稱位置字符進行比較。Java代碼以下:
/** * 功能說明:LeetCode 9 - Palindrome Number * 開發人員:Tsybius * 開發時間:2015年9月24日 */ public class Solution { /** * 判斷某數是否爲迴文數 * @param x 數字 * @return true:是,false:否 */ public boolean isPalindrome(int x) { if (x < 0) return false; if (x < 10) return true; String str = String.valueOf(x); for (int i = 0; i < str.length() / 2; i++) { if (str.charAt(i) != str.charAt(str.length() - i - 1)) { return false; } } return true; } }
END