首页 > 代码库 > [LeetCode]50 Pow(x, n)
[LeetCode]50 Pow(x, n)
https://oj.leetcode.com/problems/powx-n/
http://blog.csdn.net/linhuanmars/article/details/20092829
public class Solution { public double pow(double x, int n) { // Solution A: // return pow_Recursion(x, n); // Solution B: return pow_Shift(x, n); } //////////////////////// // Solution B: Number // // Any num can be represented by 2. private double pow_Shift(double x, int n) { if (x == 0) return 0d; if (n == 0) return 1d; boolean neg = n < 0; n = Math.abs(n); double r = 1d; while (n > 0) { if (n % 2 == 1) r *= x; x *= x; n = n >> 1; } if (neg) return 1 / r; return r; } //////////////////////// // Solution A: Recursion // private double pow_Recursion(double x, int n) { // x ^n = // x ^ (n / 2) * x (n / 2) * x (n % 2) if (x == 0) return 0; if (n > 0) return p(x, n); else return 1 / p(x, -n); } private double p(double x, int n) { if (n == 0) return 1; double v = p(x, n / 2); if (n % 2 == 0) return v * v; else return v * v * x; } }
[LeetCode]50 Pow(x, n)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。