Copy """
以31 / 3为例
-> temp = 3, divided = 28, num = 1, res = 1
-> temp = 6, divided = 22, num = 2, res = 1+2
-> temp = 12, divided = 10, num = 4, res = 1+2+4
-> (回到第一个while)
-> temp = 3, divided = 7, num = 1, res = 1+2+4+1
-> temp = 6, divided = 1, num = 2, res = 1+2+4+1+1
"""
class Solution :
def divide ( self , dividend : int , divisor : int ) -> int :
sign = - 1 if (dividend >= 0 and divisor < 0 ) or (dividend < 0 and divisor >= 0 ) else 1
dividend = abs (dividend) # 不要忘记转为正数
divisor = abs (divisor)
res = 0
while dividend >= divisor : # x里面还能分出y
temp = divisor
num = 1 # 注意初始化为1
while dividend >= temp : # 开始比较x是否大于y的倍数,一次从x里面减去最大的2^n*y
dividend -= temp
res += num # res代表temp里面有多少个y,所以在x减去temp后,res也要加在result里
temp = temp << 1
num = num << 1
if sign == - 1 :
res = - res
return min ( max ( - 2147483648 , res), 2147483647 ) # 32-bit integer limitations
Copy class Solution :
def singleNumber ( self , nums : List [ int ] ) -> int :
res = 0
for num in nums :
res = res ^ num
return res
Copy class Solution :
def getSum ( self , a : int , b : int ) -> int :
carry = 0
mask = 0x ffffffff
while b & mask != 0 :
carry = (a & b) << 1
a = a ^ b
b = carry
return a & mask if b > mask else a
Copy class Solution :
def reverseBits ( self , n : int ) -> int :
ans = 0
for i in range ( 32 ):
if n >> i & 1 :
ans |= 1 << 31 - i
return ans