Write a function: def solution(A, B) that, given two non-negative integers A and B - Interview Questions

Write a function: def solution(A, B) that, given two non-negative integers A and B, returns the number of bits set to 1 in the binary representation of the number A * B. For example, given A = 3 and B = 7 the function should return 3, because the binary representation of A* B = 3 * 7 = 21 is 10101 and it contains three bits set to 

1. Assume that:  A and B are integers within the range [0...100,000,000] In your solution, focus on correctness

Solution

def solution(A,B): 
 C =A*B 
 bin_c = bin(C).replace("0b","") #converting to binary 
 form res = [int(x) for x in str(bin_c)] #converting binary number to list of 0 and 1 
 c_1 = 0 #counter for 1 
 for i in range(len(res)): #counting the number of 1's in list 
  if res[i]== 1: 
   c_1 = c_1 + 1 
  return c_1 
print(solution(3,7)) 
print(solution(5,25)) 
print(solution(5,13))

Sharecodepoint

Sharecodepoint is the junction where every essential thing is shared for college students in the well-defined packets of codes. We are focused on providing you the best material package like Question papers, MCQ'S, and one NIGHT STUDY MATERIAL. facebook twitter youtube instagram

Post a Comment

Previous Post Next Post

Contact Form