Monotype Interview Question
Senior Software Development EngineersCountry: India
Interview Type: In-Person
The code above is incorrect, since it doesn't handle an important edge case [of 0 and negative numbers].
Handling of such edge cases is important for these kind of interview questions. Here's correct version:
bool power2(int a)
{
return (a > 0) && ((a & (a-1)) == 0);
}
You're thinking of a multiple of 2. A power of two, in binary, will be represented by 00000010, 00000100, 00001000, 00010000, etc. Thus you need to count the # of bits. If it's more than one (you can stop when you get to 2), it's not a power of 2. Or if the 1's place is 1. So it would look like this:
if(a&1) return false;
for(i = 0; i < 32; i++) {
if(a = a>>1 & 1)count ++;
if (count>1) return false;
}
if count = 1 return true;
else return false;
#include <iostream>
using namespace std;
int main()
{
int powerOfTwo;
char exit = 'n';
while( exit=='n')
{
cout << "Enter number :";
cin>> powerOfTwo;
if(powerOfTwo==0)
{
cout << "Number is 0 only.";
}
if(!(powerOfTwo &(powerOfTwo-1)))
{
cout<<"Number is Power of 2..."<<endl;
}
else{
cout<<"Number is not power of 2..."<<endl;
}
cout << "Do you want to exit ? Y/N" << endl;
cin >>exit;
}
return 0;
}
A power of 2, when represented as binary number, is one bit 1 with all the remaining bits 0.
This code below flips the rightmost bit 1 of an integer. If the resulting number becomes zero, you know it had only one bit 1 before, thus a power of 2.
- Victor December 05, 2014