## Cognzant Technology Solutions Interview Question for Software Engineer / Developers

Country: India
Interview Type: Written Test

Comment hidden because of low score. Click to expand.
4
of 4 vote

if( v && !( v & (v-1) ) ) => power of 2

!( v &(v-1) ) is sufficient except fo v = 0

Comment hidden because of low score. Click to expand.
2
of 2 vote

unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here

f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));

Reference: graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2

To understand this video you may want to watch this video

Comment hidden because of low score. Click to expand.
0
of 0 vote

for an integer to be power of 2 it should have only a single bit 1 among the whole word
therefore,
!(v&&(!v))=0, for all such numbers

Comment hidden because of low score. Click to expand.
0
of 0 vote

That's simple...

``````bool ispowerof2(int num)
{
bool ispwrof2 = false;
if(num & (num - 1) == 0)
{
ispwrof2 = true;
return ispwrof2;
}

return ispwrof2;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

// by using logical and bitwise operator we can do it.

int main()
{
int num;
scanf("%d", &num);
(!(num & (num-1)) &&printf("yes\n")) || printf("no\n");
return 0;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

For checking that the given number is a power of two or not use the algorithm given below:

Implementation:

``````bool findpower(int n){
return n && (!(n&(n-1)));``````

}

Comment hidden because of low score. Click to expand.
-2
of 2 vote

To know the given integer v is a power of 2, just apply log to v base 2 as shown below:

``````v = 2^n
==>  n = log v base 2
If n is a number (not a decimal) then
v is a power of 2
else
v is not a power of 2``````

Comment hidden because of low score. Click to expand.
0

This is great if you have two hardware instructions that don't exist on typical hardware. 1) A very fast log operation 2) A very fast "is this an integer" operation (this requires at least a slow modulus op). This is also if you don't care about the possibility of roundoff error.

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.