问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3858 访问。

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

输入: 1

输出: true

解释: 20 = 1

输入: 16

输出: true

解释: 24 = 16

输入: 218

输出: false


Given an integer, write a function to determine if it is a power of two.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3858 访问。

public class Program {

    public static void Main(string[] args) {
var n = 8;
var res = IsPowerOfTwo(n);
Console.WriteLine(res); n = 513;
res = IsPowerOfTwo2(n);
Console.WriteLine(res); Console.ReadKey();
} private static bool IsPowerOfTwo(int n) {
//先看原值是否能被2整除
//若不能整除,不是2的幂;
//若能整除,继续往下,直接<=1时为止
//最后判断值是否为1即可
while(n % 2 == 0 && (n /= 2) > 1) { }
return n == 1;
} private static bool IsPowerOfTwo2(int n) {
//2为10,4为100
//2-1为01,4-1为011
//对它们进行“与”运算
//10 & 01 = 0
//100 & 011 = 0
//得出结论,如果一个数n为2的幂,则n & (n - 1) = 0
return ((n > 0) && (n & (n - 1)) == 0);
} }

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3858 访问。

True
False

分析:

显而易见,IsPowerOfTwo 的时间复杂度为:  ,IsPowerOfTwo2 的时间复杂度为:  。

最新文章

  1. geotrellis使用(十七)使用缓冲区分析的方式解决单瓦片计算边缘值问题
  2. null和undefined区别(转)
  3. --- shell 扩展的顺序
  4. 【C#进阶系列】06 类型和成员基础
  5. 03-图片浏览器(plist的简单应用)
  6. java1.8的几大新特性(二)
  7. CSS3超酷移动手机滑动隐藏側边栏菜单特效
  8. JS - 全屏滚动
  9. C++设计模式--观察员
  10. Spring in Action --- 使用MockMvc时报异常
  11. Angularjs^1.2.9 搜索关键字高亮显示
  12. EM and GMM(Code)
  13. C语言精要总结-指针系列(二)
  14. spring boot + vue + element-ui全栈开发入门——前端编辑数据对话框
  15. C语言 &#183; 猜算式
  16. linux du查看文件所占大小
  17. json.loads()的字符串中为单引号引发的错误
  18. LSTM介绍
  19. SQLUnit 环境搭建
  20. 转 Java笔记:Java内存模型

热门文章

  1. oracle数据库备份还原命令
  2. Keras之对鸢尾花识别
  3. 服务注册与发现【Eureka】- Eureka简介
  4. 03 AMD规范的基础使用详解
  5. jmeter接口测试 -- 设置跨线程组的全局变量
  6. Google免费新书-《构建安全&amp;可靠的系统》
  7. java JDBC自我总结
  8. myBatis源码解析-日志篇(1)
  9. HTML中div嵌套div的margin不起作用
  10. 不想得手指关节炎?帮你提炼IDEA常用代码补全操作