面试篇:Java 实现 x 的 y 次方

    前两天面试的一道题,记录一下:

Guava 中的实现:

/**
   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
   * {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
   * time.
   *
   * 

Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible // failing tests public static int pow(int b, int k) { checkNonNegative("exponent", k); // 保证 k 为非负数 switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Integer.SIZE) ? (1 << k) : 0; case (-2): if (k < Integer.SIZE) { return ((k & 1) == 0) ? (1 << k) : -(1 << k); } else { return 0; } default: // continue below to handle the general case } for (int accum = 1; ; k >>= 1) { switch (k) { case 0: return accum; case 1: return b * accum; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } }


网友实现方案,参见: 点击打开链接
public class Power {

    public static double pow(double a, int b){
        //check the validity of a and b
        if(a == 0 && b == 0)
            return Integer.MIN_VALUE;

        if(a == 0)
            return 0;

        if(b == 0)
            return 1;

        if(b == 1)
            return a;

        boolean aMinus = a < 0? true: false;
        boolean bMinus = b < 0? true : false;

        int bAbs = Math.abs(b);
        double aAbs = Math.abs(a);

        //check if b is odd
        double tempAnswer;
        if( (b & 1) != 0){
            tempAnswer = pow(aAbs, bAbs - 1) * aAbs;
        }
        else{
            tempAnswer = pow(aAbs * aAbs, bAbs / 2);
        }

        if(bMinus)
            tempAnswer = 1.0 / tempAnswer;
        if(aMinus && (b&1)!= 0)
        tempAnswer *= -1;

        return tempAnswer;

    }

    public static void main(String[] args){


        System.out.println(Power.pow(0,0));
        System.out.println(Power.pow(3,0));
        System.out.println(Power.pow(3,-1));
        System.out.println(Power.pow(3,100));
        return ;
    }
}
关键还是算法

你可能感兴趣的:(Java,面试,Java,算法)