Skip to content

Commit 58fbacf

Browse files
Count number of bits to be flipped to convert A to B
1 parent ea930a4 commit 58fbacf

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

Bit_Manipulation/Count_Bits_Flip_A_B.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,20 @@
22

33

44
def count_bits_flip(a, b):
5-
return bin(a ^ b).count("1")
5+
# XOR a and b to get 1 on opposite value bit position
6+
c = a ^ b
7+
8+
# initialise the counter for 1
9+
count = 0
10+
11+
# count the number of 1s while there is 1 in a ^ b
12+
while c != 0:
13+
count += 1
14+
c &= (c-1)
15+
16+
# return the count of 1s
17+
return count
18+
619

720
# 2 = 0010
821
# 8 = 1000

0 commit comments

Comments
 (0)