判斷一個(gè)整數(shù)是否是回文數(shù)敌蜂∩细冢回文數(shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)剪侮。
示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121
輸出: false
解釋: 從左向右讀, 為 -121 需了。 從右向左讀, 為 121- 跷究。因此它不是一個(gè)回文數(shù)姓迅。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 。因此它不是一個(gè)回文數(shù)俊马。
進(jìn)階:
你能不將整數(shù)轉(zhuǎn)為字符串來解決這個(gè)問題嗎丁存?
本題思路是每次都把最高位和最低位的數(shù)給取出來然后進(jìn)行判斷,是否相等柴我,題目是比較簡單的解寝,代碼如下:
class Solution {
public boolean isPalindrome(int x) {
//負(fù)數(shù)都不滿足
if ( x < 0) return false;
int temp = x;
int bit = 0;
//算出位數(shù)bit
while (temp > 0){
temp /= 10;
bit++;
}
temp = x;
int tempBit = bit - 1;
for (int i = 0; i < bit / 2; i++){
int first = temp / (int)(Math.pow(10,tempBit));
int last = temp % 10;
if (first != last)
return false;
//去掉最高位
temp = temp % (int)(Math.pow(10,tempBit));
//去掉最低位
temp = temp / 10;
//每一次都減去兩位
tempBit = tempBit - 2;
}
return true;
}
}
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindrome-number
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)艘儒,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處聋伦。