[Leetcode] powx n x的n次方
Implement pow(x, n).
题意:计算x的次方
思路:这题的思路和sqrt的类似,向二分靠近。例如求4^5,我们可以这样求:res=4、4*4^4。就是将每次在res的基础上乘以x本身,换成,每次以x*=x的方式前行,这样时间复杂度为O(logn),代码如下:
class Solution {
public:
double pow(double x, int n)
{
double res=1.0;
for(int i=n;i !=;i/=)
{
if(i% !=)
res*=x;
x*=x;
}
return n<?/res:res;
}
};
把x的n次方划分成两个x的n/2次方相乘,然后递归求解子问题,结束条件是n为0返回1。代码:
class Solution {
public:
double pow(double x, int n)
{
if(n==) return ;
double half=pow(x,n/);
if(n%==)
return half*half;
else if(n>)
return half*half*x;
else
return half*half/x;
}
};
[Leetcode] powx n x的n次方的更多相关文章
- [LeetCode] Super Pow 超级次方
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large posi ...
- [LeetCode] Power of Four 判断4的次方数
Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Gi ...
- [LeetCode] Power of Three 判断3的次方数
Given an integer, write a function to determine if it is a power of three. Follow up:Could you do it ...
- [LeetCode] Power of Two 判断2的次方数
Given an integer, write a function to determine if it is a power of two. Hint: Could you solve it in ...
- [LeetCode] Pow(x, n) 求x的n次方
Implement pow(x, n). 这道题让我们求x的n次方,如果我们只是简单的用个for循环让x乘以自己n次的话,未免也把LeetCode上的想的太简单了,一句话形容图样图森破啊.OJ因超时无 ...
- LeetCode 342. Power of Four (4的次方)
Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example:Giv ...
- C#版(击败100.00%的提交) - Leetcode 372. 超级次方 - 题解
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. Leetcod ...
- [LeetCode] 50. Pow(x, n) 求x的n次方
Implement pow(x, n), which calculates x raised to the power n(xn). Example 1: Input: 2.00000, 10 Out ...
- [LeetCode] 231. Power of Two 2的次方数
Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: ...
随机推荐
- 2019年猪年海报PSD模板-第八部分
11套精美猪年海报,免费猪年海报,下载地址:百度网盘,https://pan.baidu.com/s/1Y3wc_r7O-Dp0mLCihJ9mtQ
- 【转】cocos2d-x如何优化内存的应用
原地址:http://cblog.chinadaily.com.cn/blog-942327-4327173.html 注:自身以前也写过cocos2d-x如何优化内存的应用,以及内存不够的情况下怎么 ...
- spark-submit配置说明
<Spark 官方文档>Spark配置 spark-1.6.0 原文地址 Spark配置 Spark有以下三种方式修改配置: Spark properties (Spark属性)可以控制绝 ...
- [Clr via C#读书笔记]Cp11事件
Cp11事件 类型之所以提供事件通知功能,是因为类型维护了一个已登记方法的列表,事件发生后,类型将通知列表登记的所有方法: 事件模型建立在委托的基础上.委托是调用回调方法的一种类型安全的方式. 设计事 ...
- Flex 布局浅析
除了 CSS 中传统的布局系统之外,CSS3还提供了一个新布局系统.在这个新的框模型中,框的子代采用水平或垂直布局,而且可将未使用的空间分配给特定的子代,或者通过“弹性”分配给应展开的子代,在各子代间 ...
- 你真的了解JAVA里的String么
Java中String类细节问题 (考察点Java内存分配问题) 1. String str1 = "abc"; System.out.println(str1 == &quo ...
- vue学习笔记(五):对于vuex的理解 + 简单实例
优点:通过定义和隔离状态管理中的各种概念并强制遵守一定的规则,我们的代码将会变得更结构化且易维护.使用vuex来引入外部状态管理,将业务逻辑切分到组件外,可以避免重复的从服务端抓取数据. 详情请参考官 ...
- vue移动音乐app开发学习(一):环境搭建
本系列文章是为了记录学习中的知识点,便于后期自己观看.如果有需要的同学请登录慕课网,找到Vue 2.0 高级实战-开发移动端音乐WebApp进行观看,传送门. 一:使用vue-cli脚手架搭建: 1: ...
- 第三课——MFC编程
一.MFC概述 1. MFC简述 MFC不仅仅是一套基础类库,更是一种编程方式. 2. MFC由来 1987年微软公司推出了第一代Windows产品,并为应用程序设计者提供了Win16(16位Wind ...
- c# 编译的dll看不见注释问题
1.项目属性---->生成----->勾选XML文档文件: 2.使用的时候该文件和dll放在一块.