如果评估整数POT(两个动力) [英] Evaluate if integer is POT (Power Of Two)

查看:117
本文介绍了如果评估整数POT(两个动力)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能显示的文件:
  <一href="http://stackoverflow.com/questions/666647/query-about-working-out-whether-number-is-a-power-of-2">Query关于制定是否数是2
电源   如何检查是否一个数是电源2

我需要一个函数体原型:

 布尔isPOT(INT X);
 

那么它将返回如isPOT(3)= FALSE,但isPOT(8)= TRUE

什么是最pretty的/简洁的算法?什么是最有效的?

PS:我很惊讶,我找不到所以这个问题,所以我完全期待有人来检测一些重复

PPS:可有人请创建POT,NP​​OT,幂的两个标签

解决方案

 布尔IsPOT(INT X)
{
    则返回(x大于0)及&安培; ((X安培;(X  -  1))== 0);
}
 

Possible Duplicates:
Query about working out whether number is a power of 2
How to check if a number is a power of 2

I require a function body for this prototype:

bool isPOT(int x);

So it would return eg isPOT(3) = FALSE, but isPOT(8) = TRUE

What is the most pretty/concise algorithm? And what is the most efficient?

PS: I am amazed that I cannot find this question on SO, so I am fully expecting someone to detect some duplicate.

PPS: can someone please create POT, NPOT, Power-Of-Two tags?

解决方案

bool IsPOT(int x)
{
    return (x > 0) && ((x & (x - 1)) == 0);
}

这篇关于如果评估整数POT(两个动力)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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