Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

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

Source by www.hackerearth.com #
 
PREVIOUS NEXT
Tagged: #bitwise #count #total #set #bits
ADD COMMENT
Topic
Name
4+9 =