← DiffPush

Fast Power

Baseline Bit Manipulation · Advanced Maths O(log n) · O(1)

Doubling the Gear Ratio Instead of Cranking It

A press needs a mechanical ratio of x^n, and the operator only has a doubling jig: each crank squares the current ratio. Reading n in binary tells the operator exactly which squarings to bank — every 1 bit contributes the current squared value to the product, and negative exponents simply invert the finished ratio.

Input: A double x and an integer n (possibly negative).

Output: The value of x raised to the power n.

Constraints

Examples

Example 1

Input: {"x":2,"n":10}
Output: 1024
Ten is 1010 in binary: square-bank twice (4, then 256... ) — the product lands on 1024.

Example 2

Input: {"x":2.1,"n":3}
Output: 9.261
Three cranks of the base, no squaring shortcuts skipped: 2.1^3 = 9.261.

Solve this in your browser →

Also on LeetCode ↗