您好,登錄后才能下訂單哦!
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、此題為判斷一個數(shù)值是否是回文數(shù),即將數(shù)值反轉(zhuǎn)后是否等于原數(shù)值,如是,則為回文數(shù);
2、先判斷數(shù)值x是否小于0,如小于0則返回false;
3、再判斷x是否等于0,如是,則返回true;
4、如上面兩種情況都不符合,則將數(shù)值x循環(huán)取余取出每一位上的數(shù)存入集合中;
5、循環(huán)將集合中的數(shù)取出,求得反轉(zhuǎn)后的數(shù)值;
6、與數(shù)值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;
}
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。