剑指Offer学习之面试题11 :数值的整数次方

来源:互联网 发布:网络推广合同注意事项 编辑:程序博客网 时间:2024/06/09 22:31

package com.www.OfferToSword;public class Solution11_1 {public static void main(String[] args) {System.out.println(power_1(2, 5));System.out.println(power_2(2, 5));System.out.println(power_2(2, 0));System.out.println(power_2(3, 1));System.out.println(power_2(0, 0));}public static double power_1(double base, int exp) {return Math.pow(base, exp);}public static double power_2(double base, int exp) {double res = 1;if (base == 0 && exp == 0) {throw new RuntimeException("error:invalid input");}if (exp == 0) {return 1;}if (exp == 1) {return base;}if (base != 0 && exp > 1) {res = power_2(base, exp << 1);}res *= res;if (exp % 2 != 0) {res = res * base;}return res;}}


原创粉丝点击