KatInterview

Implement Binary Exponentiation

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationmathbinary-exponentiationbit-manipulation

Last updated

Evaluate floating-point powers with integer exponents using logarithmic time binary exponentiation without standard library power methods.

Write a function my_pow(base: float, exponent: int) -> float that computes the value of base raised to the power of exponent ($base^{exponent}$).

You must not use built-in exponential operators or standard math exponentiation functions (such as Python's ** operator or pow()/math.pow()).

Rules & Edge Cases

  • An exponent of 0 should return 1.0.
  • For negative exponents, use the mathematical identity $x^{-n} = \left(\frac{1}{x}\right)^n$.
  • The algorithm should execute in $O(\log |exponent|)$ time complexity.

Constraints

  • -100.0 < base < 100.0
  • -2^31 <= exponent <= 2^31 - 1
  • exponent is a 32-bit signed integer.

Examples

Example 1

Input: my_pow(2, 10)

Output: 1024

Example 2

Input: my_pow(2.1, 3)

Output: 9.261000000000001

Example 3

Input: my_pow(2, -2)

Output: 0.25

Hints

Hint 1

Recall that any exponent can be decomposed into powers of 2 using its binary representation.

Hint 2

Consider how base^(2^k) can be computed repeatedly by squaring the previous term.

Hint 3

For negative exponents, convert the base to its reciprocal (1 / base) and make the exponent positive.