【Power of Two】cpp
2024-09-01 10:32:40
题目:
Given an integer, write a function to determine if it is a power of two.
代码:
class Solution {
public:
bool isPowerOfTwo(int n) {
if ( n<= ) return false;
int countOne = ;
for ( int i=; i<sizeof(n)* && countOne<=; ++i )
{
countOne += (n>>i) & ;
}
return countOne==;
}
};
tips:
首先的思路是bit-munipulation
检查int中有多少个1
学习了一个更简洁的(https://leetcode.com/discuss/45017/5-lines-o-1-space%26time-c-solution-no-hash)
自己优化了一下 一行代码AC。
class Solution {
public:
bool isPowerOfTwo(int n) {
return n<= ? false : !(n & (n-));
}
};
最新文章
- 文档分享-Activiti 5.16 用户手册
- GDI+中发生一般性错误的解决办法
- oracle 读书笔记
- uva10344 23 out of 5
- 几何不能具有Z值
- UVa11292
- InnoDB存储引擎
- 【memcache缓存专题(1)】memcache的介绍与应用场景
- idea15 如何设置代码不自动折叠
- 【转】cocos2d-x游戏开发(十四)用shader使图片背景透明
- Runloop -------iOS
- Spring Boot Web 开发注解篇
- remove集合的用法
- cv2.cvtColor Unsupported depth of input image
- Unity3D料槽设备旋转(一)
- CentOS 服务器安全设置 --摘抄自https://www.kafan.cn/edu/8169544.html
- Django - cookies 会话跟踪技术
- BZOJ 2865 字符串识别 | 后缀数组 线段树
- Docker学习笔记(一):在本地安装和配置Docker
- 在macro中怎么接着使用一些库?(遇到的例子:current_user)
热门文章
- Git-进阶-远程仓库的使用
- Codeforces Round #347 (Div.2)_A. Complicated GCD
- 基于Mybatis的Dao层开发
- log4net为什么会打印两次?
- 搭建基于Express框架运行环境
- Pop–实现任意iOS对象的任意属性的动态变化
- SpringCloud微服务基础 Eureka、Feign、Ribbon、Zuul、Hystrix、配置中心的基础使用
- Linux终端显示控制字符
- 理解volatile与synchronized
- Allowed memory size of 134217728 bytes exhausted (tried to allocate 2 bytes)