50. Pow(x, n)

image.png

快速幂

  1. func myPow(x float64, n int) float64 {
  2. //从1 向后逐步延伸
  3. if n < 0 {
  4. x = 1 / x
  5. n = -n
  6. }
  7. var pow float64
  8. pow = 1
  9. for n >= 1{
  10. if n & 1 == 1 {
  11. pow *= x
  12. }
  13. n = n >> 1
  14. x *= x
  15. }
  16. return pow
  17. }