C++ 0050.cpp
class Solution {
public:
double myPow(double x, int n) {
if (x == 0)
return x;
if (n == 0)
return 1;
int64_t N = n;
if (N < 0)
{
x = 1 / x;
N = -N;
}
double result = x;
N--;
while (N > 0)
{
if (N & 1)
{
result *= x;
N--;
}
else
{
x *= x;
N >>= 1;
}
}
return result;
}
};
Difficulty
and has an acceptance rate of about 39% (7+ million submissions).
Typical patterns to solve this problem:
- Math
- Recursion
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation computes the power of a floating-point base x raised to an integer exponent n. It follows a classic exponentiation-by-squaring strategy, augmented with early-exit checks for trivial inputs and a careful conversion of the exponent to a signed 64-bit integer to safely handle the most negative 32-bit value. The algorithm iteratively reduces the exponent while accumulating the result, using bitwise operations to distinguish odd and even states of the remaining exponent.
Early-exit handling
The function begins by addressing two special inputs that can be resolved without any iteration. When the base is zero, the mathematical result is zero for any non-zero exponent, and the code returns the base directly. When the exponent is zero, the mathematical identity x⁰ = 1 holds for any non-zero base, and the function returns 1. These checks avoid unnecessary work and also protect against division by zero later in the algorithm.
if (x == 0)
return x;
if (n == 0)
return 1;
Normalizing the exponent
The exponent n is originally a 32-bit signed integer. Converting it to a 64-bit signed integer N prevents overflow when the input is INT_MIN, whose absolute value cannot be represented in a 32-bit signed type. After the conversion, a negative exponent is handled by inverting the base (x = 1 / x) and negating the exponent (N = -N). This transformation turns the problem into computing a positive power, simplifying the loop logic.
int64_t N = n;
if (N < 0)
{
x = 1 / x;
N = -N;
}
Initializing the accumulator
The algorithm uses a variable result to accumulate the product of selected powers of x. It is initialized with the current base value, and the exponent is decremented by one because the first multiplication is already accounted for by this initialization. This design choice reduces the number of loop iterations by one.
double result = x;
N--;
Main loop - exponentiation by squaring
The core of the method is a while loop that runs while the remaining exponent N is greater than zero. Inside the loop, a bitwise test (N & 1) determines whether the current exponent is odd. If it is odd, the accumulator result is multiplied by the current base x, and the exponent is decremented to make it even. If the exponent is even, the base is squared (x *= x) and the exponent is halved using a right shift (N >>= 1). This pattern implements exponentiation by squaring, which dramatically reduces the number of multiplications compared to a naïve linear approach.
while (N > 0)
{
if (N & 1)
{
result *= x;
N--;
}
else
{
x *= x;
N >>= 1;
}
}
Edge-case coverage
The code explicitly handles the case where the base is zero, ensuring that a zero result is returned without performing division. The early return for an exponent of zero guarantees that 0⁰ yields 1, matching the conventional definition used in most programming contexts. By promoting the exponent to a 64-bit type before negation, the implementation safely processes the most negative 32-bit integer (INT_MIN), which would otherwise cause overflow when negated. The combination of these checks ensures correct behavior across the full range of valid inputs.
Performance optimizations
The algorithm avoids repeated multiplication by leveraging the binary representation of the exponent. Each iteration either multiplies the accumulator by the current base (when the least-significant bit is set) or squares the base and discards the processed bit (when the bit is zero). This reduces the total number of multiplications to roughly the number of bits set in the exponent plus the number of bits required to represent the exponent, which is far fewer than the linear count of n multiplications in a naïve loop.
Bitwise operations (& and >>) are used instead of modulo or division, providing faster execution on typical CPUs. The early decrement of N after initializing result eliminates one loop iteration, shaving off a constant amount of work. The use of a local double variable for the accumulator avoids repeated dereferencing of class members, keeping the hot loop tight and cache-friendly.
Overall, the implementation combines mathematical insight with low-level optimizations to deliver an efficient power function that works correctly for all edge cases defined by the input domain.
ELI5 - Simplified Explanation
Imagine you have a magic calculator that needs to multiply a number by itself over and over again. Think of the number as x and the number of times it needs to be multiplied as n.
First, the code checks if the number is zero. If you multiply zero by itself, the answer is always zero. Then it checks if n is zero, which is like saying you want to multiply the number zero times. In the world of math, that just gives you one.
Sometimes n is a negative number. When that happens, the computer flips the number upside down to make the math easier to handle.
After that, the code uses a smart shortcut to get to the answer quickly. Instead of multiplying the number one step at a time, it looks for ways to double the speed. If n is an odd number, it multiplies the result once and makes n smaller. If n is an even number, it multiplies the number by itself to make a bigger chunk and then cuts n in half. It keeps doing this until the work is finished. It is a very fast way to reach a very big number without doing too many boring steps.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | AdelDaniel | Dart | |||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Java | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| Shamik07 | Dart | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| AdelDaniel | Dart | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Java | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| Shamik07 | Dart | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 69: Sqrt(x)
- problem 372: Super Pow
- problem 2550: Count Collisions of Monkeys on a Polygon
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality