`
zhang_xzhi_xjtu
  • 浏览: 536410 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode] PowXN

阅读更多
package leetcode;

/**
* <pre>
* Implement pow(x, n).
* </pre>
*/
public class PowXN {
    public static class Solution2 {

        public double pow(double x, int n) {
            if (n < 0) {
                n = -n;
                x = 1 / x;
            }
            double result = 1;
            for (double f = x; n > 0; n = n >> 1) {
                if (n % 2 == 1) {
                    result *= f;
                }
                f = f * f;
            }
            return result;
        }
    }

    public static class Solution {
        public double pow(double x, int n) {
            if (n == 0)
                return 1;
            boolean minus = false;
            if (n < 0) {
                minus = true;
                n = -n;
            }

            double result = 1;
            double f = x;
            while (n > 0) {
                if (n % 2 == 1) {
                    result *= f;
                }

                f = f * f;
                n = n >> 1;
            }

            if (minus)
                return 1 / result;
            else
                return result;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution2().pow(1.000001, Integer.MAX_VALUE));
        System.out.println(new Solution().pow(-0.5, -2147483648));
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics