剑指offer题11
来源:互联网 发布:linux进程组 编辑:程序博客网 时间:2024/06/01 13:03
package jianzhioffer;import java.util.Scanner;/** * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 * */public class Solution11 {public static double Power1(double base, int exponent) { return Math.pow(base, exponent); }public static double Power2(double base, int exponent) { //累乘,复杂度为O(n) double result = 1.0; for(int i = 0;i < Math.abs(exponent);i++){ result *= base; } if(exponent<0) result = 1/result; return result;}public static double Power3(double base, int exponent) { //递归,复杂度为O(logn)//n为偶数,a^n=a^n/2*a^n/2;n为奇数,a^n=(a^(n-1)/2)*(a^(n-1/2))*a int n = Math.abs(exponent); if(n ==0) return 1; if(n == 1) return base; double result = Power3(base,n>>1); //右移一位,除以2 result*= result; if((n&1) == 1) //判断是否为奇数 result *= base; if(exponent<0) result = 1/result; return result;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);double base = sc.nextDouble();int exponent = sc.nextInt(); System.out.println(Power1(base,exponent)); System.out.println(Power2(base,exponent)); System.out.println(Power3(base,exponent));}}
阅读全文
0 0
- 剑指offer题11
- 【剑指offer】11-20题
- 【11-15】剑指offer
- 剑指Offer-11
- 剑指offer第一题
- 剑指offer-题
- 剑指offer第一题
- 剑指Offer第一题
- 剑指offer(题三)
- 剑指offer第二题
- 剑指offer第三题
- 剑指offer第四题
- 剑指offer第五题
- 剑指offer题一
- 剑指offer题二
- 剑指offer题七
- 剑指offer题六
- 【剑指offer】第二题
- vue2实现搜索功能计算属性
- 基于高通平台进行的总线、设备、驱动三者的关系简析
- 互联网时代下的短信营销
- linux shell脚本编程之hello world
- 【郑州·签约】中企动力助河南育林绿化工程打造一站式全网门户平台
- 剑指offer题11
- kotlin->第一个kotlin程序
- 斯坦福AI实验室又一力作:深度学习还能进一步扩展 | CVPR2016最佳学生论文详解
- 背包九讲——完全背包
- 1064. 朋友数(20)
- Oracle创建用户、指定表空间、导入表、删除用户、删除表空间
- opencv之分水岭算法分割及图像修补
- Leetcode-401. Binary Watch
- JAVA 对象序列化(一)——Serializable