Incrredible hulk using bitwise operator


its giving tle

hi @sp5513
In short the Question is to find he highest power of 2 which is smaller than or equals to the given number. Solution contains Bit Masking code and also attaching the algo for the code and hence you can also implement the same code without using bit masking if anyone is not comfortable with the bit masking approach. But do read the algo once.

Algo

  1. Check if the number is power of 2 .
    For e.g., n = 4 so 4 & 3 == 1 ? hence power of 2.
    ……1.1 If yes then return 1.
  2. Count the number of set bits.
  3. This count is the answer.

refer this code -->

vaibhav i cannot get the code can you plz explain me in details it will be better may be in g meet if possible

hi @sp5513

#include<iostream>
using namespace std;
int main() {
	int t;
	cin>>t;
	while(t--){
		int n;
		cin>>n;
		int ans = 0;
		while(n>0){
			n = n&(n-1);
			ans++;
		}
		cout<<ans<<endl;
	}
	return 0;
}

i hope this soln make it clear…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.