查询关于制定是否数量是2的幂 [英] Query about working out whether number is a power of 2

查看:113
本文介绍了查询关于制定是否数量是2的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用了经典的code片断:

Using the classic code snippet:

如果(X及(X-1))== 0

if (x & (x-1)) == 0

如果答案是1,那么它是假的,2不是一个权力然而,工作5(不是2的幂)和4的结果:

If the answer is 1, then it is false and not a power of 2. However, working on 5 (not a power of 2) and 4 results in:

0001 1111 0001 1111 0000 1111

0001 1111 0001 1111 0000 1111

这是4 1秒。

工作月8日和7:

1111 1111 0111 1111

1111 1111 0111 1111

0111 1111

0111 1111

0是第一,但我们有4个。

The 0 is first, but we have 4.

在此链接(的http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/)对于这两种情况下,答案从0开始,并有一个可变数目的0/1秒。这是如何应答的数量是否为2的幂?

In this link (http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/) for both cases, the answer starts with 0 and there is a variable number of 0s/1s. How does this answer whether the number is a power of 2?

推荐答案

您需要刷新自己如何二进制的作品。 5不重新presented如0001 1111(5比特上),它的重presented 0000 0101(2 ^ 2 + 2 ^ 0),和4同样不是0000 1111(4位上),而是0000 0100(2 ^ 2)。你写的数字是实际的一元的。

You need refresh yourself on how binary works. 5 is not represented as 0001 1111 (5 bits on), it's represented as 0000 0101 (2^2 + 2^0), and 4 is likewise not 0000 1111 (4 bits on) but rather 0000 0100 (2^2). The numbers you wrote are actually in unary.

维基百科,像往常一样,有一个pretty的全面概述。

这篇关于查询关于制定是否数量是2的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆