剑指Offer-其他-(2)

知识点:代码的完整性

题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

分析:一个简单的问题,就是实现库函数中的pow功能;要全面且高效

1:下面先是一个全面的代码:当指数是负数的时候;当指数为负数且底数为0的时候要考虑到;0的0次方在数学上是没有意义的。

package 计算一个整数的n次幂;

public class Solution{
    public static  double Power(double base,int exponent){
        double result = 1;//规定0的任何次方都是0,没有意义的也返回0;
        int n;
        if(exponent>0){
            n=exponent;
        }else if(exponent<0){
            if(base==0){
                System.out.println("我不知道是对还是错,不满足幂函数的定义2018.11.21还在准备头条中");
                return result;
            }
            n=-exponent;
        }else {
            return result;//这个时候是幂次为0
        }
       for(int i=0;i<n;i++){
           result*=base;
       }
        if(exponent>=0){
            return result;
        }else{
            return 1/result;
        }
    }
}

下面是测试案例

package 计算一个整数的n次幂;

public class Test {
public static void main(String[] args) {
	double out1 = Solution.Power(5, -4);
	System.out.println(out1);
	
	double out2= Solution.Power(0, 0);
	System.out.println(out2);
	
	
	double out3 = Solution.Power(0, -4);
	System.out.println(out3);
}
}

下面是运行结果
在这里插入图片描述

2:下面是更高效的一些方法(来源于《剑指Offer》)

在这里插入图片描述

代码如下(可以运行通过)***********中间的代码采用了递归的做法,减少了运算的次数,使得效率更高!!!!

public class Solution{
    public double Power(double base,int exponent){
        double result = 1;
        int n;
        if(exponent>0){
            n=exponent;
        }else if(exponent<0){
            if(base==0){
                throw new RuntimeException("我不知道是对还是错,不满足幂函数的定义2018.11.21还在准备头条中");
            }
            n=-exponent;
        }else {
            return result;//这个时候是幂次为0
        }
       //*******************************************************************************
       result = Power(base,n>>1);
        result*=result;
        //如果运行下面的代码说明:递归到了最后一层。
        if((n&1)==1){
            result*=base;
        }       
         //*******************************************************************************
        if(exponent>=0){
            return result;
        }else{
            return 1/result;
        }
    }
}

亮点体现在:

(1):用右移运算符代替了除以2;
(2):用 位与运算符和1做位于运算 代替了 求余运算符 来判断一个数是偶数还是奇数。

猜你喜欢

转载自blog.csdn.net/qq_35649064/article/details/84788996