一、思路
思路一:
- 整数转化为字符串
- 字符串翻转后和原字符串比较,如果相等则为回文数。
思路二:
- 数学方法
二、代码
思路一:
借用StringBuffer()中的reverse简化。
class Solution {
public boolean isPalindrome(int x) {
String str = Integer.toString(x);
String reverse = new StringBuffer(str).reverse().toString();
return str.equals(reverse);
}
}
思路一:
自己编写reverse()函数
class Solution {
public boolean isPalindrome(int x) {
//第二种解法
String str = Integer.toString(x);
String reverse = "";
for(int i = 0; i < str.length(); i++){
reverse = str.charAt(i) + reverse;
}
if(x < 0){
// reverse = "-" + reverse.substring(0, str.length() - 1);//翻转负数
//回文数不可能为负数
return false;
}
return str.equals(reverse);
}
}
思路二:
先用除法以及取模运算将整数的按位分离,将位反转之后重组成新的整数,判断是否相等。
注意:
- 注释中1 2的顺序不能颠倒
- 注释中 4 必须将x 的值提前保存,否则后面无法比较初始的x值
- 3中size必须提前计算,特别是遇到栈和队列这种size经常会发生变化的数据结构
class Solution {
public boolean isPalindrome(int x) {
if(x < 0){
return false;
}
int orgin = x;//4
int remainder = 0;
Stack<Integer> bitStack = new Stack<>();
while(x != 0){
remainder = x % 10;//1
x = x / 10;//2
bitStack.push(remainder);
}
int result = 0;
int size = bitStack.size();//一定要提前提出来
for(int i = 0; i < size; i++){//3
result = result + (int)(bitStack.pop() * Math.pow(10, i));
System.out.println(result);
}
System.out.println(result);
return orgin == result;
}
}