Leetcode50. Pow(x, n)
来源:互联网 发布:js判断上传文件格式 编辑:程序博客网 时间:2024/06/17 12:24
50. Pow(x, n)
1、原题
Implement pow(x, n).
Subscribe to see which companies asked this question.
2、题意解析
这道题的题意很是简单,就是让我们实现pow(x,n)这个函数。
一开始,我想到的是最简单的循环累乘,在这里我们会发现这样超时。因此要改变我们的思路。
我后面的思路是这样的:既然我们不能够使用正常的循环累乘;但是我们可以使用位运算,将一个大的自乘同过位数运算分解为一个简单的乘法。具体内容请看算法。
3、代码double myPow(double x, int n) { double res = 1; //主要是int的负整数绝对值大于正数部分。 unsigned int p; //当n为负数时,对数据进行相应的处理 if (n < 0) { p = -n; x = 1 / x; } else { p = n; } //位循环 while (p) { //当此位为1时,结果乘以当前的x值 if (p & 1) { res *= x; } //每进行一次位移,x都^2一次。 x *= x; //将p向左移一位 p >>= 1; } return res; }
阅读全文
0 0
- Leetcode50 Pow(x, n)
- Leetcode50 Pow(x, n)
- leetcode50 Pow(x, n)
- leetcode50. Pow(x, n)
- leetcode50. Pow(x, n)
- Leetcode50. Pow(x, n)
- LeetCode50 pow(x, n)
- 【LeetCode】LeetCode50 Pow(x, n)
- LeetCode50——Pow(x,n)
- leetcode50-Pow(x, n)(实现浮点数的幂运算)
- 剑指Offer 面试题11:数的整数次方(Leetcode50. Pow(x, n))【C库函数pow模拟】题解
- Pow(x, n) / Super Pow
- LeetCode: Pow(x, n)
- LeetCode Pow(x,n)
- [Leetcode] Pow(x, n)
- LeetCode: Pow(x, n)
- Leetcode: Pow(x,n)
- [LeetCode] Pow(x, n)
- 【BZOJ2796】【贪心】 Fibonacci Representation题解
- Cocoapods 使用
- 初学JavaScript,整理整理笔记(一)
- Android Service
- 电机控制 编程笔记 event1.c
- Leetcode50. Pow(x, n)
- CSS 技巧
- #if, #elif, #else, #endif 使用
- 线程的状态学习
- 关于自动化的一些问题
- Cramfs、JFFS2、YAFFS2
- axios的拦截请求与响应
- 数据结构练手
- 再谈应用环境下的TIME_WAIT和CLOSE_WAIT