classSolution(object):defisPowerOfTwo(self,number):""" input: int number return: boolean """# write your solution hereif number<=0:returnFalsewhile (number&1==0): number = self.rshift(number,1)return number ==1defrshift(self,val,n): return (val &0X7FFFFFFF) >> n
Determine the # of bits are different between 2 positive integers
xor 然后取多少个1
classSolution(object):defdiffBits(self,a,b):""" input: int a, int b return: int """# write your solution here a ^= b count =0while a !=0: count += a &1 a = self.rshift(a, 1)return countdefrshift(self,val,n): return (val &0X7FFFFFFF) >> n
如何数1: Hamming Weight
What happens if we assign a negative number to an unsigned integer
classSolution(object):defreverseBits(self,n):""" input: long n return: long """# write your solution herefor shift inrange (16): right = (n >> shift) &1 left = (n >> (31-shift)) &1if left!=right: n ^= (1<<shift) n ^= (1<<(31-shift))return n
10进制Number to 16进制
其实是0b到0X因为计算机里都是2进制,所以可以每四组一起,8421一个个抠出来;
怎么扣?(>>28)&0xF (>>24)&0xF
#这个有点问题classSolution(object):defhex(self,number):""" input: int number return: string """# write your solution here result = []if number==0:return'0x0'while number>0: res = number%16if res<10: result.append(chr(res))else: result.append(chr(res-10+ord('A'))) number = self.rshift(number, 4) result.append('x') result.append('0')return''.join(result[::-1])defrshift(self,val,n): return (val &0X7FFFFFFF) >> n