leetcode --Power of Two
来源:互联网 发布:开源证券交易软件 编辑:程序博客网 时间:2024/06/03 18:47
题目:Given an integer, write a function to determine if it is a power of two.
给定一个整形数,判断是否为2的幂,一开始想到的解题思路为使用c语言自带的计算幂的函数,循环计算
#include <Math.h>
bool isPowerOfTwo(int n) {
int i = 0;
while(n >= pow(2, i)) {
if (n == pow(2, i))
return true;
i++;
}
return false;
}
还有另一种思路,2的幂的最高位必定为1,其他为0;1、10、100...;每乘2相当于1左移一位,判断一个数是否只有最高位为1,其他位为0,只要将这个数与这个数减1得到的数做“&”运算为0则成立
bool isPowerOfTwo(int n) {
return ((n > 0) && ((n & (n-1)) == 0));
}
0 0
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- [Leetcode]Power of Two
- [leetCode] Power of Two
- leetcode --Power of Two
- leetcode: Power of Two
- LeetCode Power of Two
- [LeetCode] Power of Two
- LeetCode Power of Two
- [leetcode] Power of Two
- [Leetcode]Power of Two
- Leetcode: Power of Two
- [LeetCode]Power of Two
- leetcode | Power of Two
- 【leetcode】Power of Two
- [LeetCode]Power of Two
- [leetcode] Power of two
- LeetCode Power of Two
- <学习笔记>cas server + cas client 单点登录 原理介绍
- Android网页宽度自适应手机屏幕宽度的方法
- 对话框
- 与符号表分离程序或动态库, 如何用GDB调试
- HDU 2054 A == B ?
- leetcode --Power of Two
- 牛顿迭代法求数的平方根
- android Instrumentation 转载
- phpmyadin安装配置
- Eigen常用函数以及注意事项总结
- CoordinatorLayout
- maven中scope依赖范围与classpath的关系
- 指针函数与函数指针的区别
- Delphi异常处理try except语句和try finally语句用法以及区别