Easy-题目22:231. Power of Two
来源:互联网 发布:画化学分子式的软件 编辑:程序博客网 时间:2024/06/01 08:40
题目原文:
Given an integer, write a function to determine if it is a power of two.
题目大意:
给出一个整数,判断是不是2的幂。
题目分析:
跟上题如出一辙,但还有一种方法是利用位运算,即2的幂的最高位是1,其余位全是0这一性质,判断n和n-1按位与是否等于0来解决。@15-信安-L。
源码:(language:c)
递归解法:
bool isPowerOfTwo(int n) { return (n==0||n==1)?n:(n%2?0:isPowerOfTwo(n/2));}
按位与解法:
bool isPowerOfTwo(int n) { return (n&n-1)==0&&n>0;}
暴力枚举:
bool isPowerOfTwo(int n) { return (n==1||n==2||n==4||n==8||n==16||n==32||n==64||n==128||n==256||n==512||n==1024||n==2048||n==4096||n==8192||n==16384||n==32768||n==65536||n==131072||n==262144||n==524288||n==1048576||n==2097152||n==4194304||n==8388608||n==16777216||n==33554432||n==67108864||n==134217728||n==268435456||n==536870912||n==1073741824);}
成绩:
三种算法都是4ms,beats44.98%,众数4ms,55.02%。
0 0
- Easy-题目22:231. Power of Two
- LeetCode 231. Power of Two --Easy
- 231. Power of Two [easy] (Python)
- Leetcode 231. Power of Two (Easy) (cpp)
- 【leetcode】Power Of Two[easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- [Leetcode 231, Easy] Power of Two
- 【LeetCode】(231)Power of Two(Easy)
- <LeetCode><Easy>231 Power of Two
- LeetCode #231 - Power of Two - Easy
- Easy-题目21:326. Power of Three
- 38.leetcode题目231:231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- Android:Intent Filter 和 action 简介AndroidMainfest.xm
- ORM框架
- Easy-题目21:326. Power of Three
- H-Index
- Andriod Toast 自定义
- Easy-题目22:231. Power of Two
- Intent中的四个重要属性——Action、Data、Category、Extras
- 最大子段和问题
- Java跨域设置
- 宏、函数、宏函数,内联函数的区别
- CABasicAnimation动画--lable字体大小改变
- Easy-题目23:21. Merge Two Sorted Lists
- Android系统无法进入休眠
- 基因数据处理42之mango问题_seqdict.avro不存在解决