C#LeetCode刷题之#231-2的幂(Power of Two)
2024-10-09 12:44:49
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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 的时间复杂度为: 。
最新文章
- geotrellis使用(十七)使用缓冲区分析的方式解决单瓦片计算边缘值问题
- null和undefined区别(转)
- --- shell 扩展的顺序
- 【C#进阶系列】06 类型和成员基础
- 03-图片浏览器(plist的简单应用)
- java1.8的几大新特性(二)
- CSS3超酷移动手机滑动隐藏側边栏菜单特效
- JS - 全屏滚动
- C++设计模式--观察员
- Spring in Action --- 使用MockMvc时报异常
- Angularjs^1.2.9 搜索关键字高亮显示
- EM and GMM(Code)
- C语言精要总结-指针系列(二)
- spring boot + vue + element-ui全栈开发入门——前端编辑数据对话框
- C语言 &#183; 猜算式
- linux du查看文件所占大小
- json.loads()的字符串中为单引号引发的错误
- LSTM介绍
- SQLUnit 环境搭建
- 转 Java笔记:Java内存模型