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".