149. Power x to n
Compute x raised to n efficiently, including zero and negative exponents. A negative exponent uses a reciprocal, and a zero exponent follows the documented convention.
The smallest signed exponent cannot safely be negated in the same integer width. Floating-point multiplication, overflow, underflow, and rounding follow the precise contract below.
Example 1
Input
x=2.0, n=10
Output
1024.0
Explanation: Exponent ten uses powers corresponding to binary 1010.
Example 2
Input
x=2.0, n=-2
Output
0.25
Explanation: Normalize to base one-half and exponent two.
Example 3
Input
x=-2.0, n=3
Output
-8.0
Explanation: An odd exponent retains the negative sign.
Example 4
Input
x=2.0, n=-1024
Output
5.562684646268003E-309
Explanation: Reciprocal-first squaring preserves this subnormal instead of overflowing 2^1024 before inversion.
Constraints
-231 <= n <= 231 - 1- x is a finite binary64 number. If n is negative, x must be nonzero.
Hints
Hint 1
How can n be written as twice a smaller exponent plus one low bit?
Hint 2
Which factor represents each successive binary bit after repeated squaring?
Hint 3
Normalize a negative exponent in long, consume its low bit, shift, and square only for remaining work.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Consume only the set bits of exponent ten
2
10
"1024"