/**
* Source : https://oj.leetcode.com/problems/powx-n/
*
* Created by lverpeng on 2017/7/18.
*
* Implement pow(x, n).
*
*/
public class Pow {
/**
* 实现x^n
* 考虑n为负数
* 当n为偶数的时候,计算x*x,以期让n快速收缩
*
* @param x
* @param n
* @return
*/
public double pow (int x, int n) {
boolean sign = true; // true:正数
if (n < 0) {
n = -n;
sign = false;
}
double result = 1.0;
while (n > 0) {
if ((n & 1) == 1) {
result *= x;
}
n = n >> 1;
x *= x;
}
return sign ? result : 1.0 / result;
}
public static void main(String[] args) {
Pow pow = new Pow();
System.out.println(pow.pow(2, 3));
System.out.println(pow.pow(2, 10));
System.out.println(pow.pow(2, -3));
}
}
相关文章
- 02-18[LeetCode&Python] Problem 27. Remove Element
- 02-18[LeetCode] 286. Walls and Gates
- 02-18leetcode 207课程表
- 02-18LeetCode 课程表II(拓扑排序)
- 02-18Leetcode-5213 Play with Chips(玩筹码)
- 02-18【leetcode】207. Course Schedule
- 02-18[LeetCode]223. Rectangle Area矩形面积
- 02-18[LeetCode] Course Schedule II
- 02-18LeetCode-210. Course Schedule II
- 02-18【1】[leetcode-124] 二叉树中的最大路径和