LeetCode笔记:231. Power of Two
来源:互联网 发布:淘宝上购买飞行燃料 编辑:程序博客网 时间:2024/06/08 03:53
问题:
Given an integer, write a function to determine if it is a power of two.
大意:
给出一个整数,写一个函数判断它是否是2的次方数。
思路:
这道题和另一道判断是否是3的次方数的题目很像,但是这个更简单,因为有一个二进制的东西存在,我们要判断一个数是不是2的次方数,不用去一次次除以2,也不用用log去算,直接转换成二进制,如果是2的次方数,那一定是最高位为1,其余位均为0的二进制数,所以只用判断这个二进制数是不是符合这个情况就可以了。
此外还有一个地方要小心,与判断3的次方数的题目描述有一点不同在于,这里没说给出的是非负数。。。所以一定还对负数的情况进行判断,很阴险。
代码(Java):
public class Solution { public boolean isPowerOfTwo(int n) { if (n < 0) return false; String binaryStr = Integer.toBinaryString(n); for (int i = 0; i < binaryStr.length(); i++) { if (i == 0 && binaryStr.charAt(i) != '1') return false; else if (i > 0 && binaryStr.charAt(i) != '0') return false; } return true; }}
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
0 0
- LeetCode笔记:231. Power of Two
- leetcode笔记:Power of two
- [leetcode] 231.Power of Two
- LeetCode ||231. Power of Two
- [LeetCode]231.Power of Two
- Leetcode 231. Power of Two
- leetcode 231. Power of Two
- 231. Power of Two LeetCode
- [LeetCode]231. Power of Two
- [LeetCode]231. Power of Two
- LeetCode 231. Power of Two
- [leetcode] 231. Power of Two
- leetcode 231. Power of Two
- LeetCode *** 231. Power of Two
- leetcode 231. Power of Two
- LeetCode 231. Power of Two
- Leetcode-231. Power of Two
- #leetcode#231. Power of Two
- Jqgrid入门-操作表格的数据(二)
- Java关键字及其作用
- 并行计算中测试时间
- 自己研究了下代码混淆
- layer
- LeetCode笔记:231. Power of Two
- 数据结构实验之链表五:单链表的拆分
- 【python】python 入门<2>——modules
- 任务调度 Quartz
- 连续子数组的最大和
- 七牛技术总监肖勤:微服务架构实践经验分享
- 汇编语言的基础知识
- nginx-location及rewrite
- js字符串替换 - 无replaceAll替换所有字符串的解决方案