1. 题目说明

实现 pow(x, n) ,即计算 x 的 n 次幂函数。

2. 解题

  1. <?php
  2. class Solution {
  3. /**
  4. * @param Float $x
  5. * @param Integer $n
  6. * @return Float
  7. */
  8. public function myPow($x, $n) {
  9. if ($n < 0) {
  10. return 1 / $this->myPow($x, $n);
  11. }
  12. if ($n == 1) {
  13. return $x;
  14. }
  15. if ($n % 2) {
  16. return $x * $this->myPow($x, $n - 1);
  17. }
  18. return $this->myPow($x, $n / 2) * $this->myPow($x, $n / 2);
  19. }
  20. }
  21. $cls = new Solution();
  22. $r = $cls->myPow(3, 3);
  23. echo $r;