测试一个数是否是2的幂 [英] to test whether a number is a power of 2

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

问题描述

给出一个单行C表达式来测试一个数字是否是2的幂。

[不允许循环]

解决方案

ravi写道:


给出一个单行C表达式来测试一个数字是否是2的幂。

[不允许循环]



做自己的作业。


Brian


ravi写道:


>

给出单行C表达式来测试一个数字是否是一个电源

of 2. [不允许循环]



对于无符号整数:


if(!((n - 1)& n))put(n ispower of 2);


-

< http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

< http://www.securityfocus.com/columnists/423>

< http://www.aaxnet.com/editor/edit043.html>

cbfalconer at ma ineline dot net

-

通过 http://www.teranews.com


ravi写道:


给出单行C表达式来测试一个数字是否为2的幂。

[不允许循环]



static inline int

is_power_of_2(int x)

{

return((x& (x - 1))== 0);

}

-

------------ -------------------------------------------------- ---

Erik de Castro Lopo

--------------------------- --------------------------------------

哈马斯:伊斯兰教将征服美国和英国。

- http://www.pmw.org.il/LatestBulletins.htm#b220606


Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]

解决方案

ravi wrote:

Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]

Do your own homework.

Brian


ravi wrote:

>
Give a one-line C expression to test whether a number is a power
of 2. [No loops allowed]

For unsigned integers:

if (!((n - 1) & n)) puts("n is power of 2");

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net
--
Posted via a free Usenet account from http://www.teranews.com


ravi wrote:

Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed]

static inline int
is_power_of_2 (int x)
{
return ((x & (x - 1)) == 0) ;
}
--
-----------------------------------------------------------------
Erik de Castro Lopo
-----------------------------------------------------------------
"Hamas: Islam will conquer US and Britain."
-- http://www.pmw.org.il/LatestBulletins.htm#b220606


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

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