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

    分析

    难度 中

    来源

    https://leetcode.com/problems/powx-n/

    题目

    Implement pow(x, n), which calculates x raised to the power n (xn).

    Example 1:

    Input: 2.00000, 10
    Output: 1024.00000

    Example 2:

    Input: 2.10000, 3
    Output: 9.26100

    Example 3:

    Input: 2.00000, -2
    Output: 0.25000
    Explanation: 

    Note:

    • -100.0 < x < 100.0
    • n is a 32-bit signed integer, within the range [−231, 231 − 1]

    解答

    Runtime: 12 ms, faster than 88.92% of Java online submissions for Pow(x, n).

     1 package LeetCode;
     2 
     3 public class L50_PowXN {
     4     public double Pow(double x, int n) {
     5         double result=1;
     6         double temp=x;
     7         String binN = Integer.toBinaryString(n);
     8         int len=binN.length();
     9         //System.out.println(binN);
    10         for(int i=0;i<len;i++){
    11             int pos=len-1-i;
    12             //从低位到高位开始计算
    13             if(binN.charAt(pos)=='1'){
    14                 result*=temp;//指数位上的求和,相当于底数位上的乘积
    15             }
    16             temp*=temp;//当前位表示的大小
    17         }
    18         return result;
    19     }
    20     public double myPow(double x, int n) {
    21         double result=0;
    22         if(n==0)
    23             return 1;
    24         if(n<0)
    25             result=1/Pow(x,-n);
    26         else
    27             result=Pow(x,n);
    28         return result;
    29     }
    30     public static void main(String[] args){
    31         double x=2.0;
    32         int n=-2;
    33         L50_PowXN l50=new L50_PowXN();
    34         System.out.println(l50.myPow(x,n));
    35     }
    36 }
    Explanation:
    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    Python--BeautifulSoup4丶Tag丶Xpath丶requests+re的基础学习及使用
    c#字符串字面量
    vim操作
    序列的方法
    python数值类型与序列类型
    Linux操作学习笔记1
    Jav的10个面向对象设计原则
    JAVA面向对象基础
    二进制 八进制 十六进制
    using 的故事
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9873610.html
Copyright © 2011-2022 走看看