题目描述
- 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
暴力解法
c++
class Solution {
public:
bool isPalindrome(int x) {
if(x<0){return false;}
vector<int> tmp;
while(x != 0) {
tmp.push_back(x%10);//获取个位值
x = x/10;//获取除个位的其他位的值
}
for(int i=0;i<tmp.size();i++){
if(tmp[i]!=tmp[tmp.size()-i-1]){// 别忘了减1
return false;
}
}
return true;
}
};
Java
java中ArrayList和 int[]的区别,java 基本类型是传值的,引用类型是传址的。
class Solution {
public boolean isPalindrome(int x) {
if(x<0){return false;}
ArrayList<Integer> tmp =new ArrayList<>();
while(x != 0) {
tmp.add(x%10);
x = x/10;
}
for(int i=0;i<tmp.size();i++){
if(tmp.get(i)!=tmp.get(tmp.size()-i-1)){
return false;
}
}
return true;
}
}