x的n次幂-LintCode
来源:互联网 发布:印度历史知乎 编辑:程序博客网 时间:2024/05/03 07:07
实现 pow(x,n)
注意事项:
不用担心精度,当答案和标准输出差绝对值小于1e-3时都算正确
样例:
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
挑战 :
O(logn) time
思路:
二分法,从n减到0,令res=1,tmp=1,当n>=tmp,tmp左移一位,n=n-tmp,res乘上tmp个x,
当n< tmp,再把tmp置1,从头来过。注意n= INT_MIN 的情况,在误差允许的范围内,可以当成1/INT_MAX。
#ifndef C428_H#define C428_H#include<iostream>using namespace std;class Solution {public: /* * @param x: the base number * @param n: the power number * @return: the result */ double myPow(double x, int n) { // write your code here if (n >= 0) return Power(x, n); else { if (n == INT_MIN) return 1 / Power(x, INT_MAX); return 1 / Power(x, -n); } } double Power(double x, int n) { int num = 1; double res = 1; while (n >= num) { int tmp = 1; double y = x; while (n >= tmp) { n -= tmp; res *= y; y *= y; tmp = tmp << 1; } } return res; }};#endif
阅读全文
0 0
- Lintcode x的n次幂
- lintcode--x的n次幂
- LintCode:M-x的n次幂
- [LintCode]428.x的n次幂
- lintcode-分治-x的n次幂
- x的n次幂-LintCode
- lintcode x的n次幂
- lintcode刷题——x的n次幂
- x的n次幂
- x的n次幂
- x的n次幂
- x^n次幂
- 求x的n次幂算法Pow(x, n)
- 求x的n次幂
- x的n次幂递归求解
- N的平方次循环换算N+X次循环
- 快速计算x的n次幂 power()的实现
- P124.39(计算x的n次幂)
- 鼠标点击右键加入Edit with IDLE
- Sublime Text3 3143,3126 注册码,亲测可用!
- 为何要使用两次fork?
- 数据依赖症:当今AI领域的核心风险
- Emmet (ex-Zen Coding)— the essential toolkit for web-developers
- x的n次幂-LintCode
- Caused by: org.xml.sax.SAXParseException; lineNumber: 33; columnNumber: 23; 元素类型为 "session-factory"
- 文章标题
- centos升级内核步骤
- 程序员如何利用空余时间挣零花钱?
- CSS-列表
- 3.2.2练习3.4/3.2.2练习3.5
- 添加水印工具类
- mysql以一张表的字段为条件查询另外一张表