Code Logo

Power of Two

Published at25 Jul 2026
Basic Operations Easy 0 views
Like0

Compute 2 raised to the power of n, where n is a non-negative integer. The result is 2 multiplied by itself n times: 2^n.

For example, 2^1 = 2, 2^3 = 8, 2^5 = 32, and 2^10 = 1024. By definition, 2^0 = 1 (any non-zero number raised to the power of 0 equals 1). The input n is small enough that the result fits within a 32-bit integer (n ≤ 30).

This problem introduces exponentiation, one of the fundamental arithmetic operations. Powers of two are especially important in computer science because they appear everywhere: memory sizes (kilobytes, megabytes), binary representation (each bit represents a power of two), data structures (binary trees, heaps), and algorithmic analysis (logarithmic complexity classes).

The most straightforward implementation uses the pow function: Math.pow(2, n) in JavaScript/Java, pow(2, n) in Python and PHP, or the bit-shift operator 1 << n in languages with integer bitwise operations. The bit-shift approach works because 2^n in binary is a 1 followed by n zeros, which is exactly what 1 << n produces.

Edge cases include n = 0 (return 1) and n = 1 (return 2). The solution should handle these naturally whether using pow or bit shifting.

Example Input & Output

Example 1
Input
10
Output
1024
Explanation

2^10 = 1024

Example 2
Input
5
Output
32
Explanation

2^5 = 32

Example 3
Input
1
Output
2
Explanation

2^1 = 2

Example 4
Input
0
Output
1
Explanation

2^0 = 1

Example 5
Input
3
Output
8
Explanation

2^3 = 8

Algorithm Flow

Recommendation Algorithm Flow for Power of Two
Recommendation Algorithm Flow for Power of Two

Solution Approach

Use the pow function or bit-shift operator to compute 2 raised to n.

function solution(n) {
  return Math.pow(2, n);
}

Math.pow(2, n) raises 2 to the power n and returns the result. An alternative in languages with bitwise operators is 1 << n, which shifts the binary 1 left by n positions. For example, 1 << 3 = 8 (binary 1000). The bit-shift approach is faster because it maps directly to a single CPU instruction.

The pow function works for any base and exponent combination and returns a floating-point value, but when both operands are integers the result is exact for powers of two within the representable range. The bit-shift approach returns an integer directly.

Time complexity is O(1) for both approaches. Space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int n) {
        return 1<<n;
    }
}