Pow(x, n)算法实现_学习记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37770023/article/details/83927743

pow(x, n)算法实现_学习记录

package ps;

/**
 * @author Guozhu Zhu
 * @date 2018/11/10
 * @version 1.0
 *
 */

public class Demo {

	/* ============ Test ============ */
	public static void main(String[] args) {
		System.out.println(new Demo().exp(10, 2));
	}
	
    //时间复杂度O(n)=logn
	private int exp(int x, int n) {
	    if (n == 0) {
	       return 1;
        }
	    if (n == 1) {
	       return x;
	    } else {
	      int s;
	      int m  = n / 2;
	      s = exp(x, m);
	      if (m % 2 == 0) {
	         return s * s;
	      } else {
	         return s * s * x;
	      }
	    }
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_37770023/article/details/83927743