问题:判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
方法一:字符串反转
简单的想法是,如果能把这个整数中的每位数字顺序颠倒一下,变成的新的数字和原数字一样,那这就是回文数字。但是数字发反转要经过取余、求和、整除等一系列操作,稍显复杂。如果我们把这个数字变成字符串,那么字符串的反转相对容易。如果数字有n位,那算法时间复杂度为O(n)。
#Python
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
strs = str(x) #将数字变为字符串
if strs == strs[::-1]: #用切片对字符串进行反转
return True
else:
return False
//C++
class Solution {
public:
bool isPalindrome(int x) {
std::string str1 = to_string(x);
std::string str2 = str1;
std::reverse(str2.begin(),str2.end());
if(str1 == str2)
return true;
else
return false;
}
};
方法二:首尾逐位比较
这种方法仍然是利用字符串,但是不需要将字符串反转,而是从首位和末尾开始逐一比较,向中间靠拢,如果前后对应位置的字符不相等,那必定不是回文数字。这样对于非回文数字,不必对每位数字都进行操作。时间复杂度还是O(n)。
#Python
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x) #转化为字符串
i,j = 0,len(s) - 1 #设置首尾下标
while i <= j:
if s[i] != s[j]: #如果对应位置不相等
return False
i = i + 1;j = j - 1
return True
//C++
class Solution {
public:
bool isPalindrome(int x) {
std::string s = to_string(x);
int i = 0, j = s.length() - 1;
while(i <= j){
if(s[i] != s[j])
return false;
i ++; j --;
}
return true;
}
};