Bit Magic
Bit Magic
Find_digits(123)
Find_digits(123)
To convert binary to decimal
def binary_to_decimal(num):
res = 0
i = 1
while num:
res += num%10 * i
num = num//10
i = i * 2
print(res)
binary_to_decimal(1111011)
& operator, this operator does bitwise and operation and give the result
12 & 13 => 12
Because 12 => 00001100
13 => 00001101
& => 00001100 => 12
^ is XOR operator
0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 0
!2 ^ 13 => 1
Q5 Set a bit
class Solution:
def setKthBit(self, N, K):
res = []
i = 0
while N:
if i == K:
res.append(1)
else: res.append(N % 2)
N = N//2
i += 1
k = 1
ans = 0
for i in res:
ans += i * k
k = k * 2
return ans
Q6 Power of 2
class Solution:
def isPowerofTwo(self,n):
c = 0
while n:
if n % 2 == 1: c += 1
n = n//2
if c != 1: return False
return True
def check_num(arr):
num = 0
k = 1
for i in arr:
num += i * k
k *= 2
return num
Better solution
class Solution:
def rotate(self, N, D):
D = D % 16
t = 1 << 16
return [(N << D | N >> (16 - D)) % t, \
(N >> D | N << (16 - D)) % t]