1. Multiply a number with 2 ^n
2. Check if a number is power of 4 or not
1. Multiply a number with 2 ^n
The solution is very simple. We know the left shift operator is a 2 raised to the power of n.
Hence we do num << n, should give us the expected result.
2. Check if a number is power of 4 or not
Here we check the number of zero’s before the set bit. If the number of 0’s are even then it is a power of 4 else not.
Example:
16 in binary 10000
The number of 0’s is even before the set bit “1”. Hence it is a power of 4.
Solution in C++
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void multiply_2_n(int num, int n)
{
cout<<"The number "<<num<< " raised to 2 power of "<<n<<" is = "<< (num <<n)<<endl;
}
void check_num_power_of_4(int num)
{
int count = 0;
if ( num && !(num&(num-1)) )
{
while(num > 1)
{
num >>= 1;
count += 1;
}
}
if (count%2 == 0)
cout<<"The number is a power of 4"<<endl;
else
cout<<"The number is not a power of 4"<<endl;
}
int main()
{
int num = 16;
int n = 2;
multiply_2_n(num, n);
check_num_power_of_4(num);
return 0;
}
Output:
The number 16 raised to 2 power of 2 is = 64
The number is a power of 4