9. 回文数(简单)
给你一个整数 x
,如果 x
是一个回文整数,返回 true
;否则,返回 false
。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121
是回文,而 123
不是。
**进阶:**你能不将整数转为字符串来解决这个问题吗?
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
思路:
- 负数不是回文数
- 判断正数是否为回文数,判断反转前后的数字是否相等
- 将数字转化为字符串后判断
- 不转化字符串,利用%10和/10,将数字反转,然后判断是否相等
(1)C++
字符串的耗时长版本
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
string s = to_string(x);
string s1 = s;
reverse(s1.begin(),s1.end());
if(s1==s)
return true;
else
return false;
}
};
利用字符串指针的耗时短的版本
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
string s = to_string(x);
bool temp=true;
int i =0 , j=s.size()-1;
while(i<j){
if(s[i]!=s[j]){
temp = false;
break;
}
else{
i++;
j--;
}
}
return temp;
}
};
(2)C++(不用字符串、取数字的首尾位对比)
耗时长的版本
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int temp = x;
long long int y=0;
while(temp){
y = y*10 + temp%10;
temp=temp/10;
}
if(x==y)
return true;
else
return false;
}
};
耗时短的版本
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int len = 1;
bool temp=true;
while(x / len >= 10) { //len的1的位置为当前x的首位数字的位置
len = len * 10;
}
while(x){
int left = x/len;
int right = x%10;
if(left!=right){
temp=false;
break;
}
x = x%len;
x = x/10;
len=len/100; //因为x少了两位
}
return temp;
}
};
(2)python
字符串版本
class Solution:
def isPalindrome(self, x: int) -> bool:
if(x<0):
return False
s = str(x)
n = len(s)
for i in range(n//2):
j=-(i+1)
if(s[i]!=s[j]):
return False
return True
非字符串版本
class Solution:
def isPalindrome(self, x: int) -> bool:
if(x<0):
return False
l = 1
while(x//l >=10):
l=l*10
while(x):
left = x // l
right = x % 10
if(left!=right):
return False
x = x%l
x = x//10
l = l//100
return True