kikit
6/17/2016 - 9:14 AM

Bit Manipulation

Bit Manipulation

/*
https://www.hackerearth.com/notes/bit-manipulation/
*/

#include <iostream>
using namespace std;

bool isPowerOfTwoBit(int x){
	return (x && !(x & (x-1)));
}
bool isPowerOfTwo(int x){
	if(x==0)
		return false;
	else{
		while(x % 2 == 0)
			x /= 2;
		return (x==1);
	}
}
int main() {
	// your code goes here
	int i = 8;
	if(isPowerOfTwoBit(i))
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
		
	if(isPowerOfTwo(i))
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
	return 0;
}
#include <iostream>
using namespace std;

int count_one(int x){
	int count = 1;
	do{
		x /= 2;
		count++;
	}while(x % 2 != 0);
	return count;
}
int count_one_bit(int n){
	int count = 0;
	while(n){
		n = n & (n-1);
		count++;
	}
	return count;
}
int main() {
	// your code goes here
	int i = 5;
	cout << count_one(i) <<endl;
	cout << count_one_bit(i) <<endl;
	return 0;
}