原题目
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
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.
Follow up:
Coud you solve it without converting the integer to a string?
思路
- 将整数转换为字符串判断是否是回文数
- 首先对整数取绝对值,然后进行取余除10的操作得到其回文数字,比较原数字和回文数字是否相等判断是否是回文数
第一遍解法
# Runtime: 68 ms, faster than 98.32% of Python3
# Memory Usage: 13.3 MB, less than 55.67% of Python3
class Solution:
def isPalindrome(self, x):
x = str(x)
return x == x[::-1]
# Runtime: 76 ms, faster than 96.82% of Python3
# Memory Usage: 13.2 MB, less than 60.70% of Python3
class Solution:
def isPalindrome(self, x):
reverse = 0
x_copy = x
while x != 0:
reverse = reverse * 10 + x % 10
x = x // 10
return x_copy == reverse
网上好的解法
class Solution {
public:
bool isPalindrome(int x) {
if(x<0|| (x!=0 &&x%10==0)) return false; //负号 或 x不为0且最后一位为0 返回 false
int sum=0;
while(x>sum) //测试一半就能知道结果
{
sum = sum*10+x%10;
x = x/10;
}
return (x==sum)||(x==sum/10); //偶数位回文相等,奇数位回文等于 sum/10
}
};
自己可以改进的地方
- 提前筛选,负数和余数为 0 的数(不包括 0)直接返回 false,不用之后的判断,减少机器计算量
- 测试一半比较两个数而不用全部转换完再比较,既能节省空间也能节省时间
最简代码
class Solution:
def isPalindrome(self, x):
if x < 0 or (x != 0 and x % 10 == 0):
return False
reverse = 0
while x > reverse:
reverse = reverse * 10 + x % 10
x = x // 10
return x == reverse or x == reverse // 10
获得的思考
如果能提前将不符合的数据剔除应该有限考虑剔除,从而节省计算资源,提升算法的效率。但是好的算法需要深入的思考才能获得好的时间空间复杂度。