write a function given 2 non negative integers a and b returns number of bits set to 1 in binary representation of number a*b code example

Example 1: bitwise count total set bits

//WAP to find setbits (total 1's in binary ex. n= 5 => 101 => 2 setbits
int count{}, num{};
  cin >> num;

  while (num > 0) {
    count = count + (num & 1); // num&1 => it gives either 0 or 1
    num = num >> 1;	// bitwise rightshift 
  }

	 cout << count; //count is our total setbits

Example 2: find no of 1's in a binary number

len(''.join(str(bin(122011)).split('0')))-1

Tags:

Cpp Example