LeetCode Pow(x, n)
2015-06-28 01:33
357 查看
Description:
Implement pow(x, n).
Solution:
We can make n into into its binary form, for example n = 1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + ...
so x^n = x^(1*2^0) * x^(0*2^1) * x^(1*2^2) * x^(1*2^3) * ...
Put n into its binary form, and for each digit of n's binary form:
if 1, then multiply the current result with x, x is the x^2^i for ith digit.
Attention the n<0 condition.
Implement pow(x, n).
Solution:
We can make n into into its binary form, for example n = 1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + ...
so x^n = x^(1*2^0) * x^(0*2^1) * x^(1*2^2) * x^(1*2^3) * ...
Put n into its binary form, and for each digit of n's binary form:
if 1, then multiply the current result with x, x is the x^2^i for ith digit.
Attention the n<0 condition.
public class Solution { public double myPow(double x, int n) { double ans = 1.0; if (n == 0) return 1; boolean converse = false; if (n < 0) { n = -n; converse = true; } while (n > 0) { if (n % 2 == 1) { ans = ans * x; } n = n / 2; x = x * x; } if (converse) ans = 1.0 / ans; return ans; } }
相关文章推荐
- CRC32 Source Code
- 探究requestDisallowInterceptTouchEvent失效的原因
- Android点击20150628_必学必下载
- IOS初体验-Tom猫的开发
- LeetCode_Stack_Largest Rectangle in Histogram
- 灵悟礼品网上专卖店——总结
- Runtime.getRuntime().exec()----记录日志案例
- Codeforces Round #310 (Div. 1) B. Case of Fugitive set
- 数学之美-阅读笔记
- Java基础:动态代理在RPC框架中应用
- Oracle ->> ENABLE VALIDATE & DISABLE VALIDATE
- Tempter of the Bone
- 在JSP前台和后台传递参数乱码汇总
- Java基础:静态代理和动态代理
- A* Pathfinding Algorithm
- php 数组与数据结构
- 常用代码总结(一)
- 第一次博客2015/06/27
- 进程的退出exit() --多进程编程
- SQL注入原理讲解,很不错!