【leetcode】231. Power of Two
来源:互联网 发布:搜片大师源码 编辑:程序博客网 时间:2024/06/05 21:13
原题:
Given an integer, write a function to determine if it is a power of two.
大致意思就是判断是否为2的n次方,是则返回true否则false,这题可以很简单的用遍历来做,但是会很占用资源,根据2的幂次方的特点:当转换为2进制时开头第一位为1其他位为零,也就是说我们可以用这个特性,检测是否只有一个1或开头第一位是1且其他位为0,这里用第一种。
/** * @param {number} n * @return {boolean} */var isPowerOfTwo = function(n) { if(parseInt(n)>0){ var a=parseInt(n).toString(2); var s=a.toString().split(''); var sum=0; for(var i=0;i<s.length;i++){ if(s[i]=='1'){ sum++; } }if(sum==1){ return true; }else{ return false; } }else{ return false; } };要注意,测试的数据可能是负数,所以要判断。此处用的js的toString(2)转换为2进制和parseInt转换为整数型。
以上就是这题我的解法,如果你有更好的方法,欢迎在评论中讨论。
0 0
- [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
- 231.[Leetcode]Power of Two
- Leetcode 231. Power of Two
- mariadb(MySql)设置远程访问权限
- css设置透明度 (兼容所有浏览器)
- ListView底部添加加载更多按钮实现数据分页
- Android5.0免Root截屏,录屏
- OC-字典
- 【leetcode】231. Power of Two
- AbstractQueuedSynchronizer
- 设计模式之 模板模式(做练习题实例)
- 求完数
- Android设置EditText只能输入字母和数字
- 微信公众号开发系列
- js验证真实姓名
- freeswitch接入网络摄像头
- 单点登录之apacheds之springMVC下操作使用