Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 确定int是否为2的幂_Java_Math_Pow - Fatal编程技术网

Java 确定int是否为2的幂

Java 确定int是否为2的幂,java,math,pow,Java,Math,Pow,536870912是一个二次幂的数字,但结果是29.000000000000004,有人能解释一下吗?谢谢。如果n是2的幂,那么它的二进制表示形式将以1开头,后面只包含0 因此,您可以: public class test{ public static void main(String[] args) { int a=536870912; System.out.print((Math.log(a)/Math.log(2))); } } 无论如何,如果您的数字不是

536870912是一个二次幂的数字,但结果是29.000000000000004,有人能解释一下吗?谢谢。

如果n是2的幂,那么它的二进制表示形式将以1开头,后面只包含0

因此,您可以:

    public class test{
    public static void main(String[] args) {
    int a=536870912;
    System.out.print((Math.log(a)/Math.log(2)));
}
}

无论如何,如果您的数字不是很大,即适合整数或长范围,那么您可以按照建议进行操作,您可以使用以下方法:-

String binary = Integer.toBinaryString(a);
Pattern powerOfTwoPattern = Pattern.compile("10*");
System.out.println(powerOfTwoPattern.matcher(binary).matches());

说明:-重复将x除以2。它进行除法,直到商变为1,在这种情况下,x是2的幂,或者商在达到1之前变为奇数,在这种情况下,x不是2的幂。

下面的伪代码很容易适应java

boolean isPowerOfTwo (int x)
 {
  while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
   x /= 2;
  return (x == 1);
 }
注:它也可以在恒定时间内使用离散对数,而无需编译为字符串表示等,但需要一个基数为2的预计算离散对数表,甚至使用二进制操作,如中所示,这些方法是恒定时间,但使用机器int或long的默认表示

boolean is_power_of_two(int num)
{
    int i = Math.ceil(Math.log(num)/Math.log(2.0));
    /*while ( i >= 0 )
    {
        // note 1 is taken as power of 2, i.e 2 ^ 0
        // chnage i > 0 above to avoid this
        if ( num == (1 << i) ) return true;
        i--;
    }
    return false;*/
    // or even this, since i is initialised in maximum power of two that num can have
    return (num == (1 << i)) || (num == (1 << (i-1)));
}