论坛首页 综合技术论坛

[leetcode] PowXN

浏览 1003 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-10-25  
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