回文数
题目
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- 示例 1:
输入: 121
输出: true
- 示例 2:
输入: -121
输出: false
- 示例 3:
输入: 10
输出: false
思路
设计一个head索引和一个尾索引,遍历整个数组如果开始开始索引大于等于尾索引说明是回文。
public static boolean solution(int x){
String str = String.valueOf(x);
if(str.length() == 0){
return false;
}
int firstIndex = 0;
int lastIndex = str.length() -1;
while(firstIndex < lastIndex){
if(str.charAt(firstIndex) == str.charAt(lastIndex)){
firstIndex++;
lastIndex--;
}else{
break;
}
}
if(firstIndex == lastIndex || firstIndex > lastIndex){
return true;
}else{
return false;
}
}
总结
回文串的解法可以采用额外的空间进行判断