leetcode231
public class Solution {
public bool IsPowerOfTwo(int n) {
return ((n & (n - )) == && n > );
}
}
https://leetcode.com/problems/power-of-two/#/description
补充python的实现:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
算法思路:位运算。
2 ^ 0 = 1,二进制表示:0000 0001,(1-1)的二进制表示:0000 0000,1 & 0 = 0
2 ^ 1 = 2,二进制表示:0000 0010,(2-1)的二进制表示:0000 0001,2 & 1 = 0
2 ^ 2 = 4,二进制表示:0000 0100,(4-1)的二进制表示:0000 0011,4 & 3 = 0
leetcode231的更多相关文章
- [Swift]LeetCode231. 2的幂 | Power of Two
Given an integer, write a function to determine if it is a power of two. Credits:Special thanks to @ ...
- leetcode231 2的幂 leetcode342 4的幂 leetcode326 3的幂
1.2的幂 正确写法: class Solution { public: bool isPowerOfTwo(int n) { ) return false; )) == ; } }; 错误写法1: ...
- LeetCode231.2的幂
231.2的幂 描述 给定一个整数,编写一个函数来判断它是否是 2 的幂次方. 示例 示例 1: 输入: 1 输出: true 解释: 2^0 = 1 示例 2: 输入: 16 输出: true 解释 ...
- LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four
位运算相关 三道题 231. Power of Two Given an integer, write a function to determine if it is a power of two. ...
- LeetCode 231
Power of Two Given an integer, write a function to determine if it is a power of two. /************* ...
- leetcode & lintcode for bug-free
刷题备忘录,for bug-free leetcode 396. Rotate Function 题意: Given an array of integers A and let n to be it ...
- leetcode & lintcode 题解
刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...
随机推荐
- hdu 5285 二分图黑白染色
题意:给出 n 个人,以及 m 对互不认识的关系,剩余的人都互相认识,要将所有人分成两组,组内不能有互不认识的人,要求每组至少有一人,并且第一组人数尽量多,问两组人数或不可能时单独输出 BC 48 场 ...
- 93服务器上获取json数据
jdf u -p上传html文件,上传到page域名下:jdf u 上传css和js 上传到misc域名下: json数据放在html下,因为ajax请求是按照html路径走的,所以json数据放在h ...
- 系列文章--jQuery教程
从零开始学习jQuery (一) 开天辟地入门篇 从零开始学习jQuery (二) 万能的选择器 从零开始学习jQuery (三) 管理jQuery包装集 从零开始学习jQuery (四) 使用jQu ...
- PHP的extension_dir设置问题
PHP安装时,extension_dir的路径要设成绝对路径:extension_dir = "D:/Tools/php-7.0.5/ext", 不然如果设成extension_d ...
- python版 google密码认证器
#!/usr/bin/env python # -*- coding:utf-8 -*- import hmac, base64, struct, hashlib, time def calGoogl ...
- mysql explicit_defaults_for_timestamp参数
在mysql中:- timestamp列如果没有显式定义为null,默认会被设置为not null属性.(其它的数据类型如果没有显式定义为not null,默认是可以为null的).设置timesta ...
- C#中如何把byte[]数组转换成其他类型
http://bbs.csdn.net/topics/20447859 byte[] bytes = new byte[256]; //receive some stream from network ...
- POJ2299逆序对模板(树状数组)
题目:http://poj.org/problem?id=2299 只能相邻两个交换,所以交换一次只会减少一个逆序对.所以交换次数就是逆序对数. ps:原来树状数组还可以记录后边lowbit位的部分和 ...
- redux学习与使用
Redux: 主要概念Action,reducer,store,state 原理:dispatch ({ type:action, preload: { val } } ) --->reduce ...
- 5.验证用户名是否已经被注册:AJAXC请求
首先在 web.xml 文件中添加配置信息 <!-- 配置全局的字符集 --> <context-param> <param-name>encode</par ...