Leetcode_powx-n(c++ and python version)
来源:互联网 发布:系统还原会丢失数据 编辑:程序博客网 时间:2024/06/02 04:20
地址:http://oj.leetcode.com/problems/powx-n/
Implement pow(x, n).
思路:TLE和WA了好几次。
参考代码:
优化后c++代码:
class Solution {public: double pow(double x, int n) { double ans = 1; bool flag = true; if (n < 0) { flag = false; n = -n; } while (n) { if (n % 2 != 0) { ans *= x; } x *= x; n /= 2; } if (flag) { return ans; } return 1.0 / ans; }};
python 代码1:利用a^n = a^n/2 * a^n/2
class Solution: # @param x, a float # @param n, a integer # @return a float def pow(self, x, n): if not n: return 1 if n == 1: return x flag = True if n < 0: flag = False n = -n ans = 1.0 while n: if n & 0x1: ans *= x x *= x n /= 2 if flag: return ans else: return 1.0 / ans
python代码2:
class Solution: # @param x, a float # @param n, a integer # @return a float def pow(self, x, n): if not n: return 1 if n == 1: return x flag = True if n < 0: flag = False n = -n ans = 1.0 cnt = 0 while cnt < n: tmpow = 1 tmpans = x while cnt+tmpow*2 <= n: tmpow *= 2 tmpans *= tmpans cnt += tmpow ans *= tmpans if flag: return ans else: return 1.0 / ans
0 0
- Leetcode_powx-n(c++ and python version)
- Leetcode_count-and-say(c++ and python version)
- Leetcode_linked-list-cycle(c++ and python version)
- Leetcode_climbing-statirs (c++ and python version)
- Leetcode_pascals-triangle (updated c++ and python version)
- Leetcode_unique-paths (updated c++ and python version)
- Leetcode_path-sum (updated c++ and python version)
- Leetcode_jump-game (updated c++ and python version)
- Leetcode_two-sum (c++ and python version)
- Leetcode_longest-palindromic-substring(c++ and python version)
- Leetcode_word-break(c++ and python version)
- Leetcode_wildcard-matching(c++ and python version)
- Leetcode_valid-number(updated c++ and python version)
- Leetcode_jump-game-ii(c++ and python version)
- Leetcode_multiply-strings (updated c++ and python version)
- Leetcode_permutation-sequence(c++ and python version)
- Leetcode_next-permutation(c++ and python version)
- Regular Expression Pocket Reference: Regular Expressions for Perl, Ruby, PHP, Python, C, Java and .N
- javascript 格式化 json字符串
- awk中使用shell变量
- 【北京之旅】--程序员应聘技巧之笔试
- Oracle 11G在用EXP 导出时,空表不能导出解决
- jquery.validate----身份证号码验证
- Leetcode_powx-n(c++ and python version)
- maven(8)--创建项目工厂和设置权限
- Java学习系列(七)Java面向对象之集合框架详解(上)
- Leetcode —— Best Time to Buy and Sell Stock
- WCF的发布
- 关于ALSA的小结
- 使用Opengl绘制字体
- TI C66x DSP 系统events及其应用 - 3
- JOptionPane类提示框的一些常用的方法