野原新之助0

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 public class Solution {
 2   public long power(int a, int b) {
 3     // Write your solution here
 4     if (b == 0) return 1;
 5     long half = power(a, b/2);
 6     if (b % 2 == 0) {
 7         return half * half;
 8     } else {
 9         return half * half * a;
10     }
11   }
12 }

Q: Evaluate a to the power of b, assuming both a and b are integers and b is non-negative. 

 

User recursion to advance the process, reduce the time complexity to O(logb), instead of O(b).

Inside recursion:

  Base case is when b == 0, return 1.

  use b % 2 to determine if odd or even.

  notice the type of return value. In this problem, is "long".

posted on 2018-03-11 09:51  野原新之助0  阅读(121)  评论(0编辑  收藏  举报