Power of Two
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
2^10 = 1024
2^5 = 32
2^1 = 2
2^0 = 1
2^3 = 8
Algorithm Flow

Solution Approach
Use the pow function or bit-shift operator to compute 2 raised to 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
class Solution {
public int solution(int n) {
return 1<<n;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
