461. Hamming Distance
x^y是按位或,bin()方法将结果转成bit形式,再数1的个数
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count("1")
557. Reverse Words in a String III
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sarray = s.split(" ")
newlist = list()
for i in sarray:
newlist.append(i[::-1])
output = " ".join(newlist)
return output
476. Number Complement
n – 1为和num二进制位等长的所有位数为1的数,与num取^可以得到和num相反的数字
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = 1;
while i <= num:
i = i << 1
return (i - 1) ^ num
226. Invert Binary Tree
递归,还是很好做的
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root