Binary Search:leetcode 50 Pow(x,n)

The article explains how to implement binary search method to find Pow(x,n) with the best approach.


Realize the functionality of Pow(x, n) ,i.e, compute \(x^n\).

Example 1:

1Input:x = 2.00000, n = 10
2Output:1024.00000

Example 2:

1Input:x = 2.00000, n = -2
2Output:0.25000
3Explain:2^{-2} = (1/2)^2 = 1/4 = 0.25

Solution:

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func myPow(x float64, n int) float64 {
 8	if n >= 0 {
 9		return quickMul(x, n)
10	}
11	return 1.0 / quickMul(x, -n)
12}
13
14func quickMul(x float64, n int) float64 {
15	if n == 0 {
16		return 1
17	}
18	y := quickMul(x, n/2)
19	if n%2 == 0 {
20		return y * y
21	}
22	return y * y * x
23}
24
25func main() {
26	fmt.Println(quickMul(1.5, 2)) // print 2.25
27}

Translations: