问题描述
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?
解决思路
题目要求不能将int转为String解决,那就用int的方法解决。比较简单,从后往前取模的结果成10,循环累加,最后和一开始的x比较就行了。
问题
要注意的是,需要将x先给temp,再对temp进行处理,第一次做的时候,全程对x进行处理导致最后x变成0,怎样都是return false,最后ac不通过,看了半天没看懂哪里错了。
代码
class Solution {
public boolean isPalindrome(int x) {
//corner case
if(x == 0) return true;
if(x < 0) return false;
int temp = x;
int res = 0;
while(temp != 0){
res = res * 10 + temp % 10;
temp /= 10;
}
if(res == x) return true;
else return false;
}
效率探究
时间效率: O(n)
空间效率: O(1)