Palindrome Number
问题描述
Determine whether an integer is a palindrome. Do this without extra space. 判断一个整型数字是否为回文。并且不能再占用额外空间
解决方法一
该问题和上一个字符反转类似。同样可以采用字符反转的方法进行验证判断。
参考代码:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if 0<= x < 10:
return True
elif x >= 10:
y=str(x)[::-1] # 字符反转
if x == int(y):
# 判断是否相等 return True
else:
return False
else:
return False
测试情况如下:
11507 / 11507 test cases passed.
Status: Accepted
Runtime: 209 ms
貌似y变量占用了额外空间,但测试仍然通过了
解决方法二:
同样采用数字拆分后组合
代码:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
z=x
if x < 0:
return False
else:
y = 0
while x != 0:
y = y * 10 + x % 10
x /= 10
if z == y:
return True
else:
return False
leetcode测试结果: 11507 / 11507 test cases passed. Status: Accepted Runtime: 259 ms
这里也额外占用内存也通过了。
Hamming Distance
问题描述
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 2**31. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0)
The above arrows point to positions where the corresponding bits are different.
求x,y两个正整数的汉明距离。汉明距离:就是两个数二进制不同位数的格式 比如 1,4 就有两位不同
解决方法
两个数字按位进行或运算,结果不同的为1,相同为0,然后求结果中为1的位数,即为两个数的汉明距离
代码
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
n = x ^ y
num=0
for i in bin(n)[2:]:
if i is "1":
num += 1
return num
测试结果:
149 / 149 test cases passed. Status: Accepted Runtime: 39 ms