461. 汉明距离
class Solution:
def hammingDistance(self, x, y):
return bin(x ^ y).count('1')
面试题 05.03. 翻转数位
class Solution:
def reverseBits(self, num: int) -> int:
num = bin(num) if num >= 0 else bin(((1 << 32) - 1) & num)
n = num.split("0")
ans = -1
for i in range(1, len(n)):
ans = max(ans, n[i-1].count("1") + n[i].count("1") + 1)
return min(32, ans)
231. 2 的幂
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n-1) == 0
# n 二进制最高位为 1,其余所有位为 0;n−1 二进制最高位为 0,其余所有位为 1
1290. 二进制链表转整数
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
cur = head
res = 0
while cur:
# res = res * 2 + cur.val
res = (res<<1) + cur.val
cur = cur.next
return res