AceYourInterviews
Checking sign-in…

149. Power x to n

IntermediateBinary exponent decomposition with widened signed exponent normalization

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Consume only the set bits of exponent ten

2
10
"1024"