首页 > 试题广场 >

数值的整数次方

[编程题]数值的整数次方
  • 热度指数:826492 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
实现函数 double Power(double base, int exponent),求base的exponent次方。

注意:
1.保证base和exponent不同时为0。
2.不得使用库函数,同时不需要考虑大数问题
3.有特殊判题,不用考虑小数点后面0的位数。

数据范围: ,保证最终结果一定满足
进阶:空间复杂度 ,时间复杂度

示例1

输入

2.00000,3

输出

8.00000
示例2

输入

2.10000,3

输出

9.26100
示例3

输入

2.00000,-2

输出

0.25000

说明

2的-2次方等于1/4=0.25    
推荐
    /**
     * 1.全面考察指数的正负、底数是否为零等情况。
     * 2.写出指数的二进制表达,例如13表达为二进制1101。
     * 3.举例:10^1101 = 10^0001*10^0100*10^1000。
     * 4.通过&1和>>1来逐位读取1101,为1时将该位代表的乘数累乘到最终结果。
     */
    public double Power(double base, int n) {
    	double res = 1,curr = base;
    	int exponent;
    	if(n>0){
    		exponent = n;
    	}else if(n<0){
    		if(base==0)
    			throw new RuntimeException("分母不能为0");  
    		exponent = -n;
    	}else{// n==0
    		return 1;// 0的0次方
    	}
    	while(exponent!=0){
			if((exponent&1)==1)
				res*=curr;
			curr*=curr;// 翻倍
			exponent>>=1;// 右移一位
		}
		return n>=0?res:(1/res);        
  	}

编辑于 2015-09-20 14:56:57 回复(142)
Python
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        self.result = 1
        if exponent>0:
            for i in range(exponent):
                self.result = self.result * base
            return self.result
        if exponent < 0:
            for i in range(-exponent):
                self.result = self.result * base
            return 1/self.result
        if exponent ==0 :
            return 1


发表于 2021-05-21 16:26:11 回复(0)
class Solution:
    def Power(self, base, exponent):
        # write code here
        return pow(base, exponent)
发表于 2020-10-03 10:41:07 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if base == 0:
            return 0
        if base == 1:
            return 1
        else:
            return (pow(base, exponent))
        
如果不考虑上面两种情况:

则:

发表于 2020-07-23 17:42:59 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        def quick_mul(x, n):
            # 快速幂法
            if not n:
                return 1.0
            y = quick_mul(x, n//2)  # 递归
            if n%2 ==0:
                return y * y 
            else:
                return y * y * x
        if exponent<0:
            base = 1 / base
            exponent = -exponent
        return quick_mul(base, exponent)

编辑于 2020-06-22 09:37:24 回复(0)
class Solution:
    def Power(self, base, exponent):
        # write code here
        if base == 0 and exponent==0:
            return None
        return base**exponent
发表于 2020-04-08 14:34:30 回复(0)
  • 注意考虑exponent为负数的情况
  • 使用二分提高将时间提高到lgn
  • 使用 >> 1实现除2
  • 使用 &1可判断奇偶 
    class Solution:
      def Power(self,base,exponent):
          if base == 0:
              return 0
          else:
              res = [1,base]
              for i in range(2,abs(exponent)+1):
                  res.append(res[int(i>>2)] * res[int((i + 1) >> 2)])
              if exponent >= 0 :
                  return res[abs(exponent)]
              else:
                  return 1/res[abs(exponent)]
    

s = Solution()
ans = s.power(3,-3)
print(ans)

```

发表于 2020-02-24 19:56:36 回复(0)

数值的整数次方(理论+python实现)

1.理论

题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
请在这里输入引用内容
保证base和exponent不同时为0

这道编程题考验求解数值的幂的过程,这里的幂要注意几种情况:

  1. 正整数
  2. 负整数

在求解幂为负整数的时候,注意在最后返回结果时,对其取倒数。

最直接的求解方法是:直接循环求数值积,但这种方式的时间复杂度是o(n),有兴趣的朋友再优化优化吧。

2.python实现

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        # 求数值幂,要注意整数包含正整数和负整数
        # 如果幂是负整数,对结果取倒即可
        # ------------------------
        # method 1:使用内置方法
        if (base==0.0 and exponent!=0) or (base!=0.0 and exponent==0) or (base!=0.0 and exponent!=0):
            return base ** exponent

        # -------------------------
        # method 2:暴力循环法 时间复杂度 o(n)
        res=1
        for i in range(abs(exponent)):
            res*=base
        if exponent<0:  # 考虑负整数的情况
            res=1/res
        return res

        # --------------------------
        # method 3:
编辑于 2020-02-24 17:44:36 回复(0)
class Solution:
    def Power(self, base, exponent):
        if base == 0 and exponent == 0:
            return 0
        else:
            return base**int(exponent)

发表于 2020-02-23 20:37:13 回复(0)
二分法Python解法
程序有点冗长跪求各位更优雅的写法
mark = 0
class Solution:
    def Power(self, base, exponent):
        global mark
        if base == 0:#排除0
            return 0
        if exponent == 0:
            return 1
        if exponent < 0: #把复指数数变成正数
            exponent = -exponent
            mark = 1
        if exponent == 1:
            return base
        if exponent%2 == 0:
            if mark == 1:
                return (1/self.Power(base, exponent/2))**2
            else:
                return self.Power(base, exponent/2)**2
        else:
            if mark == 1:
                return (1/base)*(1/self.Power(base, exponent/2))**2
            else:
                return base*self.Power(base, exponent/2)**2

发表于 2020-02-17 13:48:20 回复(0)
这是一个更简洁的快速幂的递归的写法,看了很多回答,都不是这种写法。但是想了半天,还是觉得这样更简洁。
C++写法:
class Solution {
public:
    double Power(double base, int exponent) {
        int e = exponent;
        if (e < 0) {
            e = -e;
            base = 1 / base;
        }
        if (e == 1) {
            return base;
        } else if (e == 0) {
            return 1;
        }
        if (e & 1) {
            return base * Power(base * base, e >> 1);
        } else {
            return Power(base * base, e >> 1);
        }
    }
};
python写法:
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        if exponent < 0:
            base = 1.0 / base
            exponent = - exponent
        e = exponent
        if e == 1:
            return base
        elif e == 0:
            return 1
        if e & 1:
            return base * self.Power(base * base, e >> 1)
        else:
            return self.Power(base * base, e >> 1)


发表于 2020-01-21 02:16:48 回复(0)
# -*- coding:utf-8 -*-
# 解题思路:考察代码的完整性,注意exponent为负的情况
# 有一个技巧:base的exponent次方:
# 当exponent为偶数时,pow(b, e) = pow(b, e/2) * pow(b, e/2)
# 当exponent为奇数时,pow(b, e) = pow(b, e/2) * pow(b, e/2) * b
# 当exponent为正数时,直接按上述表达式求值
# 当exponent为负数时,先求e的绝对值,然后用1除以pow(b,e)
# 当exponent为0时,直接返回1
class Solution:
    def Power(self, base, exponent):
       return pow(base, exponent)

    def pow(self, base, exponent):
        if exponent == 0:
            return 1

        if exponent == 1:
            return base

        ex = abs(exponent)
        result = pow(base, ex / 2) * pow(base, ex / 2)
        if ex % 2 == 1:
            result *= base

        if exponent < 0:
            return 1/result

        return result

发表于 2020-01-15 19:50:07 回复(0)
因为两者不同时为0
所以考虑指数的正、负及0的情况就好
1. 正  --  n个数相乘
2. 0   --  直接返回1
3. 负  -- 指数为负即指数为正时的取倒数
class Solution:
    def Power(self, base, exponent):
        # write code here
        total = 1
        if exponent == 0:
            return total
        elif exponent > 0:
            for i in range(1,exponent+1):
                total *= base
            return total
        else:
            t = -exponent
            for i in range(1,t+1):
                total *= base
            return 1/total

 
发表于 2019-12-18 22:20:34 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        return pow(base, exponent)
简单粗暴
发表于 2019-12-04 14:59:54 回复(0)
python常用公式pow(a,b),可以用来求a的b次方,其中要求b为整数
发表于 2019-10-30 20:42:53 回复(0)
python中可以直接求出结果
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        return base**exponent


编辑于 2019-10-18 19:49:56 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if base == 0 and exponent == 0 :
            return none
        return base**exponent
Hint:
其实不是Hint,没太理解考察的要点是什么.....
编辑于 2019-09-22 00:27:48 回复(0)
    def Power(self, base, exponent):
        return base**exponent
善用Python
发表于 2019-09-14 23:10:37 回复(0)
class Solution:
    def Power(self, base, exponent):
        # write code here
        return base**exponent
#一行搞定
发表于 2019-08-19 13:22:51 回复(0)
python:

class Solution:
    def Power(self, base, exponent):
        # write code here
        方法一:快速幂
        if base==0:
            return 0
        if exponent==0:
            return 1
        n=abs(exponent)
        res=1
        tmp=base
        while(n>0):
            if (n&1==1):
                res=res*tmp
            n=n>>1
            tmp=tmp*tmp
        return res if exponent>0 else 1/res
        方法二:
        return base**exponent
        方法三:
        import math
        return math.pow(base,exponent)
        方法四:
        return pow(base,exponent)
        方法五:
        if base==0:
            return 0
        if exponent==0:
            return 1
        result=1
        n=abs(exponent)
        for _ in xrange(n):
            result=result*base
        return result if exponent>0 else 1/result

发表于 2019-08-11 10:46:21 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        

        if exponent == 0:
            return 1
        elif exponent == -1:
            return 1/base
        elif exponent == 1:
            return base
        elif exponent % 2 == 1:
            return self.Power(base,exponent // 2) * self.Power(base,exponent // 2) * base
        else:
            return self.Power(base,exponent // 2) * self.Power(base,exponent // 2)
        # write code here
发表于 2019-08-06 17:10:25 回复(0)

问题信息

难度:
75条回答 163661浏览

热门推荐

通过挑战的用户

查看代码