Check Power of 2 in PHP

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Bits & binary

What you’ll learn

  • Which numbers count as powers of two (1, 2, 4, 8, 16…) and why that matters in computing.
  • The classic bit test n & (n - 1), explained without assuming you already love binary.
  • Two complete PHP programs: test one value, then list every power of two from 1 to 20.
  • A live preview, a divide-by-two loop alternative, and usual edge cases.

Overview

Start with 1. Multiply by 2 each step: 1, 2, 4, 8, 16, 32, … Those are powers of two. The job is to tell whether a given positive integer appears in that list. The fast PHP trick looks at the number’s binary shape: powers of two are exactly the positive integers whose binary form has one single 1 and the rest 0s.

Bitwise test

One line: positive and (n & (n - 1)) == 0. The page unpacks what that means.

Live preview

Try 16, 12, or 1 before compiling.

Range listing

Second program prints 1 2 4 8 16 for numbers 1–20, matching the classic homework output.

Prerequisites

Tiny PHP programs, if, and the idea that & in this lesson is bitwise AND inside integer expressions.

  • Basic PHP syntax, echo, functions, and integer comparisons.
  • Optional comfort: counting in binary (1, 10, 100, 1000 for 1, 2, 4, 8).

What is a power of 2?

A power of two is any value 2k where k is a whole number and k ≥ 0. So the list begins 1, 2, 4, 8, 16, 32, …

You can also think: start at 1 and keep doubling. If you ever land on your target, it is a power of two. If you skip over it or never hit it exactly, it is not.

Why the n & (n - 1) trick works

Write n in binary. Subtracting 1 borrows from the lowest 1 bit: that bit becomes 0, and every bit to its right flips to 1. If n had exactly one 1 bit (true for powers of two), then n - 1 has 0 everywhere n had 1. The bitwise AND then lines up zeros with that single one and the result is all zeros.

Mini example: n = 8
  1. Binary for 8 is 1000 (one lonely 1).
  2. n - 1 = 7 is 0111 in binary.
  3. AND pairs bits: 1000 & 0111 = 0000. So (n & (n - 1)) == 0.
Why also check n > 0?

Zero is not a power of two in this tutorial’s definition, and the n - 1 pattern is awkward for negative numbers. The condition n > 0 keeps the story clean.

Quick examples

16 Power of 2
Because
2 × 2 × 2 × 2 = 16
12 Not
Because
Doubling: 1, 2, 4, 8, 16 — you jump past 12.
1 Power of 2
Because
20 = 1 (start before any doubling).

Live preview

Uses the same rule as the PHP samples for JavaScript safe integers: positive and (n & (n - 1)) === 0. For small n it also shows a short binary string so the “one 1 bit” idea is visible.

Enter a nonnegative integer. Very large values are capped so the tab stays responsive.

Live result
Press “Run check” to see the verdict.

Algorithm

Goal: decide whether a positive integer n equals 2k for some k ≥ 0.

Bitwise method (used in the programs)

Reject non-positive

If n <= 0, return false.

Clear the lowest 1 bit test

Compute n & (n - 1). If the result is 0, n had at most one 1 bit; together with n > 0, that means exactly one 1 bit — a power of two.

📜 Pseudocode

Pseudocode
function isPowerOfTwoBitwise(n):
    if n <= 0:
        return false
    return (n & (n - 1)) = 0

function isPowerOfTwoLoop(n):
    if n <= 0:
        return false
    while n > 1 and n mod 2 = 0:
        n ← n / 2
    return n = 1
1

Check a single number

Classic interview one-liner: require n > 0, then use n & (n - 1). Change $number or read input with trim(fgets(STDIN)) in PHP CLI.

php
<?php
function isPowerOfTwo(int $num): bool
{
    return ($num > 0) && (($num & ($num - 1)) === 0);
}

$number = 16;

if (isPowerOfTwo($number)) {
    echo $number . " is a power of 2.\n";
} else {
    echo $number . " is not a power of 2.\n";
}
?>

Explanation

($num > 0) && ...

Guard. Rules out zero and negatives before touching $num - 1 in a way that would muddy the pattern.

($num & ($num - 1)) === 0

Single 1-bit test. For positive $num, this is zero exactly when $num is 1, 2, 4, 8, …

2

Powers of 2 from 1 to 20

Reuses the same helper and keeps the program fully integer-based in PHP.

php
<?php
function isPowerOfTwo(int $num): bool
{
    return ($num > 0) && (($num & ($num - 1)) === 0);
}

echo "Power of 2 in the range 1 to 20:\n";

for ($i = 1; $i <= 20; $i++) {
    if (isPowerOfTwo($i)) {
        echo $i . " ";
    }
}

echo "\n";
?>

Explanation

The outer loop tries every i. Only 1, 2, 4, 8, 16 pass inside 1–20 because the next power, 32, is larger than 20.

Notes

Equivalent form. Some codebases write $num && !($num & ($num - 1)). For integers, that is another way to spell “nonzero and a single 1 bit” — the extra ! flips the zero compare.

Logarithms. You can test whether log($n, 2) is an integer in PHP, but floating rounding can hurt large values. Prefer bits or the divide-by-two loop for exactness.

Interview: say “positive integer with exactly one set bit” out loud, then show n & (n-1).

❓ FAQ

It is a whole number you can write as 2 multiplied by itself some whole number of times. Examples: 1 (because 2^0 = 1), 2, 4, 8, 16, 32&hellip; Non-examples: 3, 5, 6, 12.
Yes. By convention 2^0 = 1, so the sequence usually starts 1, 2, 4, 8, 16&hellip; The programs on this page treat 1 as a power of 2.
In binary, subtracting 1 flips the lowest 1 bit and every 0 to its right. If n has exactly one 1 bit, that clears the only 1 and the AND with n becomes zero. If n has zero or more than one 1 bit, the test fails.
Zero would make n - 1 negative, and the neat bit pattern story breaks for the interview form. Negative numbers are not counted as powers of two here.
Yes. While n is even and n &gt; 1, divide n by 2. If you end at 1, it was a power of two. Handle n == 1 separately; reject n &lt;= 0.
No. Every power of two after 1 is even, but many even numbers (like 6) are not powers of two.

🔄 Input / output examples

Example 1 prints one line. Use $number = (int)trim(fgets(STDIN)); for interactive PHP CLI runs.

Input numberTypical line (Example 1)
1616 is a power of 2.
1212 is not a power of 2.
11 is a power of 2.
00 is not a power of 2.

Edge cases

Most bugs come from forgetting the n > 0 guard or mixing up bitwise & with logical &&.

n = 0

Zero

Not a power of two here. Without num > 0, the bitwise story is misleading.

Negatives

Signed integers

Reject n <= 0 for this lesson. Extending the definition to negatives is not standard for “power of two” in interviews.

& vs &&

Bitwise vs logical

num & (num - 1) uses bitwise AND on integers. The outer test often uses && so short-circuiting can skip work when num is zero (style varies; both guards are fine if written clearly).

⏱️ Time and space complexity

ApproachTime (single n)Extra space
Bitwise n & (n-1)O(1)O(1)
Divide by 2 loopO(log n)O(1)
Scan [1, U] with per-value testO(U)O(1)

Summary

  • Idea: powers of two are 1, 2, 4, 8, … — positive integers with a single 1 in binary.
  • Code: (n > 0) && ((n & (n - 1)) == 0) is the usual constant-time test.
  • Fallback: keep halving even numbers; you should finish at 1 only for powers of two.
Did you know?

Many sizes in computing are powers of two: bytes group into kilobytes, memory chips, and texture widths. That is why “is this number a power of two?” shows up beside bit masks, alignment, and binary trees.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful