How to get number of bits set to 1 of a binary number?

Algorithm problem:

Write a function given 2 non-negative integers a and b returns number of bits set to 1 in the binary representation of number a*b

Solution

Following is the solution of the above problem using JavaScript:


    function getCountSetBits(num) {
        let count = 0;
        while (num) {
            count += num & 1;
            num >>= 1;
        }
        return count;
    }

    function solution(A, B) {
        if (A < 0 || A > 100000000) return 0;
        if (B < 0 || B > 100000000) return 0;

        const multiplyResult = A * B;
        return getCountSetBits(multiplyResult);
    }

    console.log(solution(5, 25));