How do you calculate log base 2 in Java for integers?

后端 未结 10 2158
情话喂你
情话喂你 2020-11-29 15:12

I use the following function to calculate log base 2 for integers:

public static int log2(int n){
    if(n <= 0) throw new IllegalArgumentException();
            


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 16:17

    Some cases just worked when I used Math.log10:

    public static double log2(int n)
    {
        return (Math.log10(n) / Math.log10(2));
    }
    

提交回复
热议问题