题目描述(简单)
题目含义:判断数字是不是回文数。
解法一
比较简单,先把数字逆序输出。然后将原来的数字和逆序之后的数字进行比较。如果两者相同,返回true,否则返回false。
public class Palindrome_Number {
public static int reverse(int x) {
int ans = 0;
int x_copy=x;
if(x < 0) return false;
while(x!=0){
int pop = x % 10;
x = x / 10;
ans = ans * 10 + pop;
}
return x_copy == ans;
}
public static void main(String args[]) {
int x=121;
boolean answer=reverse(x);
System.out.println(answer);
}
}
如果将上述代码转换成python语言,首先false需要大写转换为False,其次在JAVA中/表示取整,而python用//表示取整。
class Solution(object):
def isPalindrome(self, x):
ans = 0
x_copy=x
if(x < 0):
return False
while(x!=0):
pop = x % 10
x = x // 10
ans = ans * 10 + pop
return x_copy == ans
时间复杂度:和求转置一样,x 有多少位,就循环多少次,所以是 O(log(x)) 。
空间复杂度:O(1)。
解法二
采取的是倒置的方法。举例来说13531.我们只需要比较右半边31倒叙之后13是否和左半部分13相同。相同则返回true。当然,这里我们需要考虑数字分为偶数和奇数的情况。本质上没有什么差异。
class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
int digit=(int)(Math.log(x)/Math.log(10)+1);//总位数
int revert=0;
int pop=0;
//倒置右半部分
for(int i=0;i<digit/2;i++) {
pop=x %10;
revert=revert*10+pop;
x/=10;
}
if(digit %2==0 && x==revert) return true;
if(digit %2!=0 && x/10==revert) return true;
return false;
}
}
时间复杂度:循环 x 的总位数的一半次,所以时间复杂度依旧是 O(log(x))。
空间复杂度:O(1),常数个变量。