## Qualcomm Interview Question

Software Engineer in TestsJust check the last bit of given number, if it is set, its not the power of 2

Bool isPowerof2 = ((A & 0x1) >0) ? (FALSE) : (TRUE);

static void Main(string[] args)

{

int number = enter any no;

int quotient = 0;

int mod = 0;

while(number >= 2)

{

mod = number % 2;

quotient = number / 2;

if (mod == 0 && number >= 2)

{

number = quotient; ;

continue;

}

else break;

}

if (mod == 0)

{

Console.WriteLine("number power of 2");

}

else

{

Console.WriteLine("number not power of 2");

}

Console.ReadLine();

}

#include "stdafx.h"

#include <conio.h>

#include <iostream>

using namespace std;

bool powerof2(int x)

{

unsigned int i = 0;

int count = 0;

bool p2 = true;

if (x == 1)

{

return false;

}

else

{

while (i < 31)

{

if (x & 1 << i)

{

++count;

if (count > 1)

{

p2 = false;

break;

}

}

i++;

}

}

return p2;

}

int _tmain(int argc, _TCHAR* argv[])

{

bool p2 = powerof2(32);

return 0;

}

#include "stdafx.h"

#include <conio.h>

#include <iostream>

using namespace std;

bool powerof2(int x)

{

unsigned int i = 0;

int count = 0;

bool p2 = true;

if (x == 1)

{

return false;

}

else

{

while (i < 31)

{

if (x & 1 << i)

{

++count;

//// If Count > 1 it is not a power of 2

if (count > 1)

{

p2 = false;

break;

}

}

i++;

}

}

return p2;

}

int _tmain(int argc, _TCHAR* argv[])

{

bool p2 = powerof2(32);

return 0;

}

To check if the given number is a power of 2 we have to go through the given below algorithm, i.e. we have to first that the & operator with the previous number's ! operation will either return 1 or 0 and then the && comparison operator will return true or false deciding the number is a power of 2 or not.

Implementation:

```
#include<bits/stdc++.h>
using namspace std;
bool findresult(int n){
return n && (!(n & (n - 1));
}
```

For negative numbers add this line:

bool isPow2(int n){

n=n<0?-n:n;

return !(n & (n-1));

}

How? Look at the exponential graph, it never goes below 0 past the x axis.

Also, 2^x = -4, give me x. You can't. The power of any positive integer, such as 2, is always positive. Remember that a number raised to a negative number is just a positive inverse. Therefore, this case is invalid.

for unsigned integer nummbers:

- strezh October 08, 2010bool isPow2(int n)

{

return !(n & (n-1)) && n;

}