判斷一個整數(shù)是否是回文數(shù)桐猬。回文數(shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)刽肠。
// 回文數(shù)轉(zhuǎn)換為String類型判斷
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
String s = String.valueOf(x);
char []ss = s.toCharArray();
int start = 0;
int end = ss.length-1;
while (start < end) {
if (ss[start] ==ss[end]){
start++;
end--;
} else {
return false;
}
}
return true;
進(jìn)階:
你能不將整數(shù)轉(zhuǎn)為字符串來解決這個問題嗎溃肪?
// 回文數(shù),數(shù)字方法判斷
public boolean isPalind(int x){
if (x < 0) {
return false;
}
int a = 0;
int b = x;
int s = 0;
while (b != 0){
a = b%10; // 給定值對10取余
b = b/10; // 給定值對10取整
if (s == 0) {
s = a;
} else {
s = s*10 + a;
}
}
if (s == x) {
return true;
} else {
return false;
}
}