Check if the number has bits in alternate pattern
The solution contains 3 steps:
1. Right shift the number by 1
2. XOR the above result with the original number
3. Add 1 to the above result and check if the above result is 2^n.
As we know XOR operator returns 1 only if both bits are different. Hence when we right shift the digit and add it with itself will produce all ones, any other pattern will produce at-least one zero. This covers steps 1 and 2.
In step 3 we add the XOR result with 1 and check if the result is 2^n. If it can be represented, then the number doesn’t have alternative bits, else it has.
Powers of two in binary look like this:
1: 0001
2: 0010
4: 0100
8: 1000
Check if the number has equal number of set and unset bits
For this we iterate all the bits of the number, and check if the bit is set or unset and increment the value.
Solution in C++
/* * File : bitwise_operations.cpp * Author : ajay.thousand@gmail.com * Copyright: @ prodevelopertutorial.com */ #include<iostream> #include<vector> #include<string> using namespace std; void check_number_has_alternate_bits(int num) { int x = num >> 1; int y = x ^ num; ( y & (y+1)) ? cout<<"The number does not have alternate bits" : cout<<"The number have alternate bits"; cout<<endl; } void check_number_has_equal_set_unset_bits(int num) { int set = 0; int unset = 0; while(num) { if(num & 1) set ++; else unset ++; num = num >> 1; } if(set == unset) cout<<"The number has equal set and unset bits"<<endl; else cout<<"The number does not have equal set and unset bits"<<endl; } int main() { int num_1 = 10; int num_2 = 12; cout<<"For num = "<<num_1<< " the result is "<<endl; check_number_has_alternate_bits(num_1); check_number_has_equal_set_unset_bits(num_1); cout<<"\n\nFor num = "<<num_2<< " the result is "<<endl; check_number_has_alternate_bits(num_2); check_number_has_equal_set_unset_bits(num_2); return 0; }
Output:
For num = 10 the result is The number have alternate bits The number has equal set and unset bits For num = 12 the result is The number does not have alternate bits The number has equal set and unset bits