def solution(A, B):
result = 0
while B > 0:
result += A & 1
A >>= 1
B >>= 1
return result
This solution focuses on correctness.
Some notes:
A & 1 performs a bitwise AND of A and 1. This checks if the least significant bit of A is 1.
A >>= 1 performs arithmetic right shift of A by 1 bit. This divides A by 2.
We continually divide A and B by 2 until B reaches 0.
At each step, we increment result if A & 1 evaluates to 1, meaning the least significant bit of A is 1.
So this counts the number of 1 bits in the binary representation of A * B.
Time complexity: O(log n) since we halve A and B in each iteration of the loop.
Space complexity: O(1)