您好,登錄后才能下訂單哦!
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:Coud you solve it without converting the integer to a string?
1、此題為判斷一個數值是否是回文數,即將數值反轉后是否等于原數值,如是,則為回文數;
2、先判斷數值x是否小于0,如小于0則返回false;
3、再判斷x是否等于0,如是,則返回true;
4、如上面兩種情況都不符合,則將數值x循環取余取出每一位上的數存入集合中;
5、循環將集合中的數取出,求得反轉后的數值;
6、與數值x比較是否相等,如是,則返回true,否則返回false。
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
} else if (x == 0) {
return true;
} else {
int temp = x;
int result = 0;
List<Integer> list = new ArrayList<Integer>();
while (temp != 0) {
list.add(temp % 10);
temp = temp / 10;
}
for (int i = 0; i < list.size(); i++) {
result = result + list.get(i) * (int)Math.pow(10, list.size() - 1 - i);
}
if (result == x) {
return true;
} else {
return false;
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。