2024.5.31 回文整数判断
字符串法:
class Solution {
public boolean isPalindrome(int x) {
String str = String.valueOf(x);//把整数转为一个一个字符元素放到字符串里
int p1 = 0,p2 = str.length()-1;//设置两个哨兵,一个在字符串首位,一个在尾部
while(p1 < p2){//判断是否对比完所有元素
if(str.charAt(p1) != str.charAt(p2)){
return false;//如果出现非对称现象,则对比失败
}
p1++;
p2--;//移动对比元素
}
return true;//遍历完所有元素,发现满足回文条件
}
}
反向判断法:
//temp一位一位添加,judge一位一位减少,最后judge成为temp
class Solution {
public boolean isPalindrome(int x) {
int temp = x;//用temp过渡一下目标x
int judge=0;//用来最后与x进行判断
if(temp == 0) return true;//找出特殊情况
while(temp > 0){
judge = judge*10 + temp % 10 ;//一点点把judge上升至于x一致
temp /= 10;//把temp一位位减少,从而让末尾元素添加到judge
}
return judge == x;//判断反转的judge是否与x一致
}
}