zoukankan      html  css  js  c++  java
  • 【Leetcode】50. Pow(x, n)

    Implement pow(x, n).

    Example 1:

    Input: 2.00000, 10  Output: 1024.00000
    

    Example 2:

    Input: 2.10000, 3   Output: 9.26100
    package medium;
    
    public class L50MyPow {
        // 调用Math.pow() 函数
        public double mypow(double x, int n) {
            double nn = n;
            return Math.pow(x, nn);
        }
    
        //本题就x的n次方,如求2的4次方。可以4个2相乘,也可以先两个2相乘,之后两个4在相乘。
        public double myPow(double x, int n) {
            //防止n越界2147483647,用long类型的N来代替n
            long N = n;
            double result = 1.0;
            // double类型的x 判断x是否为0
            if ((x - 0.0 < -0.000000000001) && n < 0) {
                return 0.0;
            }
            //指数小于零,求得的数是用负指数相反数求得的值的倒数。
            if (N < 0) {
                N = -N;
                x = 1 / x;
            }
            double current_product = x;
            for (long i = N; i > 0; i /= 2) {
                if ((i % 2) == 1) {
                    result = result * current_product;
                }
                current_product = current_product * current_product;
            }
            return result;
        }
    
        public static void main(String[] args) {
            L50MyPow cc = new L50MyPow();
            //测试负数的整数次方。  4.0
            System.out.println(cc.myPow(-2, 2));
            System.out.println("!!!!!!!!!!!!!!!!!!!");
            //小数的负数次方   2.543114507074558E-5
            double re = cc.myPow(34.00515, -3);
            System.out.println(re);
            //小数的大正整数次方次方 0.0
            System.out.println(cc.myPow(0.00001, 2147483647));
        }
    }
  • 相关阅读:
    批量插入以及数据存在重复就进行更新操作
    插件-过滤器
    NamedParameterJdbcTemplate
    菜鸟python---文件 + 操作
    菜鸟python---文件操作
    菜鸟python---以后会遇到的坑
    菜鸟python---二次编码
    菜鸟python---基础数据类型补充
    菜鸟python---深浅拷贝
    菜鸟python---集合
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8418420.html
Copyright © 2011-2022 走看看