public class test{
public static void main(String[] args) {
int a=536870912;
System.out.print((Math.log(a)/Math.log(2)));
}
}
536870912是一个2的幂数,但结果是29.000000000000004,有人可以解释一下吗?感谢。
答案 0 :(得分:3)
如果n
强大2
,则其二进制表示形式将以1
开头,并且仅包含0
秒。
所以,你可以这样做:
String binary = Integer.toBinaryString(a);
Pattern powerOfTwoPattern = Pattern.compile("10*");
System.out.println(powerOfTwoPattern.matcher(binary).matches());
无论如何,如果您的号码不是很大(即适合int
或long
范围),那么您可以按照here
答案 1 :(得分:0)
您可以使用以下方法: -
boolean isPowerOfTwo (int x)
{
while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
x /= 2;
return (x == 1);
}
Explanation
: - 反复将x除以2.它除以直到商变为1,在这种情况下x是2的幂,或者商在达到1之前变为奇数,在这种情况下x不是两个人的力量。
答案 2 :(得分:0)
伪代码跟随,很容易适应java
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)));
}
注意它也可以在恒定时间内使用离散对数来完成,而不需要编译为字符串表示等,但需要一个预先计算的基本2
离散对数表,甚至使用二进制操作与https://stackoverflow.com/a/600306/3591273中一样,这些方法是常量时间,但使用机器int
或long