Bird
0
0
DSA Cprogramming~5 mins

Check if Number is Power of Two in DSA C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean for a number to be a power of two?
A number is a power of two if it can be written as 2 raised to some integer exponent, like 1, 2, 4, 8, 16, etc.
Click to reveal answer
intermediate
Which bitwise operation can quickly check if a number is a power of two?
Using (n & (n - 1)) == 0 checks if n is a power of two, because powers of two have only one bit set.
Click to reveal answer
intermediate
Why must we check if the number is greater than zero before using (n & (n - 1))?
Because zero and negative numbers are not powers of two, and (n & (n - 1)) == 0 is true for zero, so we exclude zero by checking n > 0.
Click to reveal answer
beginner
What is the output of the function if the input number is 16?
The function returns true because 16 is 2^4, a power of two.
Click to reveal answer
beginner
Write the C code snippet to check if an integer n is a power of two.
int isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }
Click to reveal answer
Which of these numbers is NOT a power of two?
A10
B8
C16
D32
What does the expression (n & (n - 1)) == 0 check for?
AIf n is zero
BIf n is a power of two
CIf n is negative
DIf n is odd
Why do we check n > 0 before applying (n & (n - 1)) == 0?
ABecause it improves performance
BBecause negative numbers are powers of two
CBecause zero also satisfies (n & (n - 1)) == 0 but is not a power of two
DBecause it checks if n is odd
What is the output of isPowerOfTwo(1)?
ATrue
BFalse
CError
DDepends on compiler
Which of these is a correct way to check if n is a power of two in C?
Areturn n % 2 == 0;
Breturn n & (n - 1);
Creturn n == 0 || n == 1;
Dreturn n > 0 && (n & (n - 1)) == 0;
Explain how to check if a number is a power of two using bitwise operations.
Think about how powers of two look in binary.
You got /4 concepts.
    Write a simple C function to check if a number is a power of two and explain why it works.
    Use (n & (n - 1)) == 0 condition.
    You got /4 concepts.