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

    50. Pow(x, n)

    1、快速幂:

    (1)递归解法:

    (2)迭代解法:

    package 数组;
    
    public class Pow {
        public static void main(String[] args) {
            Pow pow = new Pow();
            System.out.println(pow.myPow(2, -2147483648));
            System.out.println(pow.towjinzhi(21));
        }
    
        // 5^7=5^3*5*3*5
        // 5^3=5*5*5
        // 5^(-7)=5^(-3)*5^(-3)*5^(-1)
        public double myPow(double x, int n) {
            // int类型的负数比整数大一位,例如:int类型的-2147483648取负,还是-2147483648
            // 因此要转成long类型的
            long N = n;
            if (n < 0) {
                return 1 / quickPow(x, -N);
            }
            return quickPow(x, N);
        }
    
        // 迭代的方式求
        public double quickPow(double x, long n) {
            double result = 1.0;
            double contribute = x;
            while (n > 0) {
                // 二进制位为1,计入贡献
                if (n % 2 > 0) {
                    result = result * contribute;
                }
                contribute = contribute * contribute;
                n = n / 2;
            }
            return result;
        }
    
        // 求一个数的二进制
        public String towjinzhi(int n) {
            StringBuilder sb = new StringBuilder();
            while (n != 0) {
                sb.append(n % 2);
                n = n / 2;
            }
            return sb.reverse().toString();
        }
    
        // 递归的方式求
        public double quickPow1(double x, int n) {
            if (n == 0) {
                return 1;
            }
            double y = quickPow1(x, n / 2);
            if (n % 2 != 0) {
                return y * y * x;
            } else {
                return y * y;
            }
        }
    }

    。。

  • 相关阅读:
    建立文件结构
    PCL类的设计结构
    如何编写新的PCL类
    PCL推荐的命名规范(2)
    PCL推荐的命名规范(1)
    PCL中异常处理机制
    如何增加新的PointT类型
    hdoj 1728 逃离迷宫
    ny710 外星人的供给站
    ny714 Card Trick
  • 原文地址:https://www.cnblogs.com/guoyu1/p/15584119.html
Copyright © 2011-2022 走看看