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,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...
随机推荐
- Sort An Unsorted Stack
Given a stack of integers, sort it in ascending order using another temporary stack. Examples: Input ...
- 虚拟机CentOS的NAT模式联网和SecureCRT远程登录管理工具
Cenos7 发生了很大的变化,不过也是直接配置网络,从启网卡,从启机器,crt链接 https://blog.csdn.net/gebitan505/article/details/54584213 ...
- stenciljs 学习十三 @stencil/router 组件使用说明
@stencil/router 组件包含的子组件 stencil-router stencil-route-switch stencil-route stencil-route-link stenci ...
- PHP中开启gzip压缩的2种方法
网页开启gzip压缩以后,其体积可以减小20%~90%,可以节省下大量的带宽,从而减少页面响应时间,提高用户体验. php配置改法: 复制代码代码如下: zlib.output_compression ...
- centos下yum安装pip失败
[root@wfm ~]# yum -y install pip Loaded plugins: fastestmirror, refresh-packagekit, securityLoading ...
- maven 知识点2
maven 命令: table th:first-of-type { width: 500px; } table th:nth-of-type(2) { } 命令 含义 mvn help:effect ...
- C#代码规范和质量检查工具
代码风格检查:StyleCop The StyleCop tool provides warnings that indicate style and consistency rule violati ...
- python初始环境安装
Python下载地址 Python官网:https://www.python.org/ 在该网可以下载Python最新及历史版本.可以下载基于Windows或其它操作系统的版本. Python安装 本 ...
- UDP丢包问题
1. 问题描述 PC-A向PC-B发送UDP packet(共16K bytes),如果B机木有及时Read,UDP包将大量丢失. 2. 原因及解决 因为B木有及时接收,socket缓冲区放不下了. ...
- HttpURLConnection与HttpClient浅析---转
HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...