回文数
有两种解题思路:
一:将数字转换成字符串形式,首尾逐个比较。
二:将数字从末尾取模,并累加成新的数字,在比较是否相等,相等即为回文数。
class Solution{
public boolean isPalindrome(int x){
if(x < 0) return false; //为负数时不可能存在回文数
Integer s = x;
String str = s.toString();
char c1,c2; //用于保存首尾字符
for(int i = 0; i < str.length() / 2; i++){
c1 = str.charAt(i);
c2 = str.charAt(str.length - 1 - i); //字符串最后一个字符是\0
if(c1 != c2){
return false;
}
}
return true;
}
}
第二种方法:
class Solution{
public boolean isPalindrome(int x){
if(x < 0) return false;
int cur = 0; //用于保存倒序的数
int num = x;
while(num != 0){
cur = cur * 10 + num % 10;
num /= 10;
}
return x == cur;
}
}