Determine whether an integer is a palindrome. Do this without extra space.
java:
通过int转换为string,看string是否首位与相应的位相等,判断是不是palindrome
public class Solution {
public boolean isPalindrome(int x) {
if (x == 0) return true;
if (x < 0) return false;
String s = String.valueOf(x);
int i = 0;
int j = s.length();
while(i<j){
if (!s.substring(i,i+1).equals(s.substring(j-1,j))){
return false;
}
i++;
j--;
}
return true;
}
}
python:
思路:把x每次都除以10,余数乘以十叠加,看是否相等。
class Solution:
# @return a boolean
def isPalindrome(self, x):
if x<0:
return False
ret = 0
abc = x
while x>0:
ret = ret*10 +x%10
x = x/10
if ret == abc:
return True
else:
return False
本文提供了一种不使用额外空间判断整数是否为回文的方法。通过将整数转换为字符串进行逐位比较(Java版),以及通过反转整数进行对比(Python版),实现了两种高效算法。
260

被折叠的 条评论
为什么被折叠?



