201
Title description:
Given a range [m, n], where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range (including the two ends of m, n).
Example:
Answer:
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
'''
0 与谁与都为 0
因为 只要有一个0,那么无论有多少个 1都是 0
比如:从 5到 7
5:0 1 0 1
6:0 1 1 0
7:0 1 1 1
-----------
0 1 0 0
代码如下:
i=0
while m!=n:
m>>=1
n>>=1
i+=1
return m<<i
'''
while n>m:
n&=(n-1)
return n
231
Title description:
Given an integer, write a function to determine whether it is a power of 2.
Example:
Answer:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
#位运算
if n<=0:
return False
if (n&n-1)==0:
return True
return False
268
Title description:
Given an array nums containing n numbers in [0, n], find the number in the range [0, n] that does not appear in the array.
Example:
Answer:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
#异或抵消 1^1^2^2^3 = 3
res=len(nums)
for i in range(len(nums)):
res^=nums[i]
res^=i
return res
338
Title description:
Given a non-negative integer num. For each number i in the range 0 ≤ i ≤ num, count the number of 1s in its binary number and return them as an array.
Example:
Answer:
class Solution:
def countBits(self, num: int) -> List[int]:
"""
1: 0001 3: 0011 0: 0000
2: 0010 6: 0110 1: 0001
4: 0100 12: 1100 2: 0010
8: 1000 24: 11000 3: 0011
16:10000 48: 110000 4: 0100
32:100000 96: 1100000 5: 0101
由上可见:
1、如果 i 为偶数,那么f(i) = f(i/2) ,因为 i/2 本质上是i的二进制左移一位,低位补零,所以1的数量不变。
2、如果 i 为奇数,那么f(i) = f(i - 1) + 1, 因为如果i为奇数,那么 i - 1必定为偶数,而偶数的二进制最低位一定是0,
那么该偶数 +1 后最低位变为1且不会进位,所以奇数比它上一个偶数bit上多一个1,即 f(i) = f(i - 1) + 1。
:type num: int
:rtype: List[int]
"""
ret=[0]
for i in range(1,num+1):
if i%2==0:
ret.append(ret[i//2])
else:
ret.append(ret[i-1]+1)
return ret
371
Title description:
Do not use the operators + and-, calculate the sum of two integersa and b .
Example:
Answer:
class Solution:
def getSum(self, a: int, b: int) -> int:
return sum([a,b])