剑指offer 13.数值的整数次方
- 题目:https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
- 思路:
- 几次方就乘几次
- 有一个优化的思路就是比较麻烦,可以把整数次方转换成正整数次方,然后把次方数整成2进制的,加起来!可以少乘很多次,比如说8次方,本来a要乘以8次;如果把8转换成二进制,就只需要乘3次((a*a)*(a*a))*((a*a)*(a*a))
- 启发或者坑
- 要考虑到负整数
- 要考虑到1次方
- 代码
class Solution { public: double Power(double base, int exponent) { if (exponent == 0) return 1; bool negativeflag = false; if (exponent < 0) { exponent = - exponent; negativeflag = true; } double res = base; for (int i = 1; i < exponent; i++) { res *= base; } if (negativeflag) res = 1.0/res; return res; } };