leetcode解题报告233——Power of Two
2015-07-08 10:06
337 查看
Given an integer, write a function to determine if it is a power of two.
题目属于easy。前两种解法是一个意思,很容易想到;第三种解法最好(没想到)。
代码:
题目属于easy。前两种解法是一个意思,很容易想到;第三种解法最好(没想到)。
代码:
package bitmanipulation; //Given an integer, write a function to determine if it is a power of two. public class PowerofTwo { public boolean isPowerOfTwo(int n) { if (n <= 0) { return false; } String s = Integer.toBinaryString(n); if (s.charAt(0) == '0') { return false; } else { for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == '1') { return false; } } } return true; } public boolean isPowerOfTwo2(int n) { if (n <= 0) { return false; } while (n > 0) { if (n != 1 && n % 2 == 1) { return false; } n = n >> 1; } return true; } public boolean isPowerOfTwo3(int n) { if (n <= 0) { return false; } return (n & (n - 1)) == 0; } /** * @param args */ public static void main(String[] args) { System.out.println(new PowerofTwo().isPowerOfTwo3(16)); } }
相关文章推荐
- STL----空间配置器
- WCF - Creating WCF Service
- NSDictionary、NSMutableDictionary的基本用法
- 2015年最有价值的30个响应式WORDPRESS主题
- Solution 20: 字符串转整数问题
- TCP中的MSS解读(转)
- 贾扬清:希望Caffe成为深度学习领域的Hadoop
- Apache日志的一些操作命令技巧
- 一个PHP实现的轻量级简单爬虫
- 线性布局匹配全屏竟然不管用
- Serializable:serialVersionUID
- PostgreSQL中的SQL语句示例
- AF_INET与套接字
- Volley动态获取图片
- 资产负债率
- Unity扩展方法
- Ubuntu 14.04 Android 使用Maven一个 用例project
- linux系统下file使用的magic文件格式说明
- NSArray、NSMutableArray基本用法
- android BLE