LEETCODE-Power of Two
来源:互联网 发布:xcode使用教程c语言 编辑:程序博客网 时间:2024/05/21 14:44
Power of Two
Given an integer, write a function to determine if it is a power of two.
One:
简单的利用while循环
判断输入的n在整除最多的2后是否为1;
#include<iostream>using namespace std;bool isPowerOfTwo(int n) { while( (n % 2) == 0 && n >= 2) n = n / 2; if( n == 1) return 1; else return 0;}int main (){ int n; bool a; cin >> n; a = isPowerOfTwo(n); cout << a;}
Two:
通过观察发现:
2-1;4-10;8-100;16-1000;32-10000;64-100000......All power of two 的2进制都是只有最前边一位为1,其他位为0;
这些数n与n-1进行位运算&都是0;
(例如:32-10000 , 31-1111;
10000
& 01111
=00000)
所以有
#include<iostream>using namespace std;bool isPowerOfTwo(int n) { if( n > 0 &&(n & (n-1)) == 0) return 1; else return 0;}int main (){ int n; bool a; cin >> n; a = isPowerOfTwo(n); cout << a;}
位运算:
#include<iostream>using namespace std;int main (){ int n,m; cin >> n; cin >> m; cout << ( n & m );}
Input: n = 8(100); m = 10(110);
Output: 8(100);
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
- Android中滑屏实现----手把手教你如何实现触摸滑屏以及Scroller类详解
- JAVA 猜拳游戏三局两胜版
- JAVA 第二个程序
- 为什么Intent传递值会失败?
- 2.24
- LEETCODE-Power of Two
- 中国剩余定理
- lintcode-子集17
- 从零开始编写图片加载库(四)之图片缓存MemoryCache
- POJ 1840:Eqs 哈希求解五元方程
- 标准库bind函数中使用占位符placeholders
- 带有进度显示的文件拷贝模块
- python将对象写入文件,以及从文件中读取对象
- 夜深的窗,星空的床,外星的女人,想象的放荡,逻辑的流氓,懒了,忘了,跑了。。。