defcountOnes(x: int) -> int: ones = 0 while x > 0: x &= (x - 1) ones += 1 return ones
实现 pow(x,
n) ,即计算 x 的 n
次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defmyPow(self, x: float, n: int) -> float: # 快速幂 if x== 0: return0 res = 1 if n < 0: x, n = 1 / x, -n while n: if n & 1: res *= x x *= x n >>= 1# n // 2 return res
classSolution: defhammingWeight(self, n: int) -> int: res = 0 while n: res += 1 n &= n - 1 return res defhammingWeight(self, n: int) -> int: res = 0 while n: if n&1 == 1: res += 1 n >>= 1 return res
写一个函数,求两个整数之和,要求在函数体内不得使用
“+”、“-”、“*”、“/” 四则运算符号。
1 2 3 4 5 6 7
classSolution: defadd(self, a: int, b: int) -> int: # 无进位和: 异或运算^ 规律相同 # 进位: 与运算& 规律相同(并需左移一位) if b == 0: return a return add(a ^ b, (a & b) << 1)
classSolution: defsingleNumbers(self, nums: List[int]) -> List[int]: ret = functools.reduce(lambda x, y: x ^ y, nums) div = 1 while div & ret == 0: div <<= 1 a, b = 0, 0 for n in nums: if n & div: a ^= n else: b ^= n return [a, b]
classSolution: defsingleNumber(self, nums: List[int]) -> int: counts = [0] * 32 for num in nums: for j inrange(32): counts[j] += num & 1 num >>= 1 res, m = 0, 3 for i inrange(32): res <<= 1 res |= counts[31 - i] % m return res if counts[31] % m == 0else ~(res ^ 0xffffffff)
给定一个非负整数 n ,请计算 0 到
n 之间的每个数字的二进制表示中 1
的个数,并输出一个数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defcountBits(self, n: int) -> List[int]: # o(nlogn) defcountbits(x: int) -> int: ones = 0 while x > 0: x &= (x - 1) ones += 1 return ones return [countbits(i) for i inrange(n + 1)] defcountBits(self, n: int) -> List[int]: bits, high = [0], 0 for i inrange(1, n + 1): if i&(i - 1) == 0: high = i bits.append(bits[i - high] + 1) return bits