Discover a tiny trick that makes checking powers of two lightning fast!
Why Check if Number is Power of Two in DSA C?
Imagine you have a big list of numbers, and you want to find out which ones are powers of two, like 1, 2, 4, 8, 16, and so on. Doing this by dividing each number repeatedly by 2 and checking if you end up with 1 can take a lot of time and effort, especially if the list is very long.
Manually dividing numbers by 2 over and over is slow and can easily lead to mistakes, especially if you forget to check for edge cases like zero or negative numbers. It also wastes time when you have to do this for many numbers.
Using a simple bit trick, you can quickly check if a number is a power of two by looking at its binary form. This method is very fast and reliable, and it works instantly even for very large numbers.
int isPowerOfTwo(int number) {
if (number <= 0) return 0;
while (number % 2 == 0) {
number /= 2;
}
return number == 1;
}int isPowerOfTwo(int number) {
return number > 0 && (number & (number - 1)) == 0;
}This lets you instantly identify powers of two, enabling faster algorithms and smarter decisions in programs that rely on binary operations.
In computer graphics, checking if a texture size is a power of two helps optimize memory and performance, because many graphics systems work best with power-of-two dimensions.
Manual division is slow and error-prone.
Bitwise check is fast and simple.
Useful in many computing tasks involving binary data.
