Question

Write a function: that, given two non-negative integers A and B, returns the number of bits...

Write a function: 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: In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment

3 0
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #2

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


answered by: codegates
Add a comment
Answer #1

int countbits(unsigned int a, unsigned int b) {

unsigned int n = a * b;

unsigned int count = 0;

    while (n) {

        count += n & 1;

        n >>= 1;

    }

    return count;

}

Add a comment
Answer #3

def checkSorted(a, b):

    output = a*b

    if output == 0:

        return 0

    else:

    binResult = bin(output)[2:]

    return binResult.count("1")

 

result = checkSorted(3,7)

print(result)


answered by: anonymous
Add a comment
Know the answer?
Add Answer to:
Write a function: that, given two non-negative integers A and B, returns the number of bits...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT