LeetCode Power of Two (2的幂)
题意:判断1个数n是否刚好是2的幂,幂大于0。
思路:注意会给负数,奇数。对于每个数判断31次即可。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<||(n&)==&&n>) return false;
unsigned int t=;
while(t<n) //注意爆int
t<<=;
if(t==n) return true;
return false;
}
};
AC代码
一行代码,更巧的写法:
如果一个数n是2的某次幂,那么他应该是100000这样的,那么n-1会是0111111这样的,两者相与n&(n-1)必定为0。
class Solution {
public:
bool isPowerOfTwo(int n) {
return n> && !(n&(n-)) ;//100和011的&应该是0才对
}
};
AC代码
LeetCode Power of Two (2的幂)的更多相关文章
- C#LeetCode刷题之#342-4的幂(Power of Four)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4058 访问. 给定一个整数 (32 位有符号整数),请编写一个函 ...
- C#LeetCode刷题之#326-3的幂(Power of Three)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3867 访问. 给定一个整数,写一个函数来判断它是否是 3 的幂次 ...
- C#LeetCode刷题之#231-2的幂(Power of Two)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3858 访问. 给定一个整数,编写一个函数来判断它是否是 2 的幂 ...
- [LeetCode] Power of Four 判断4的次方数
Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Gi ...
- [LeetCode] Power of Three 判断3的次方数
Given an integer, write a function to determine if it is a power of three. Follow up:Could you do it ...
- [LeetCode] Power of Two 判断2的次方数
Given an integer, write a function to determine if it is a power of two. Hint: Could you solve it in ...
- Leetcode Power of Two
Given an integer, write a function to determine if it is a power of two. 题目意思: 给定一个整数,判断是否是2的幂 解题思路: ...
- LeetCode Power of Four
原题链接在这里:https://leetcode.com/problems/power-of-four/ 题目: Given an integer (signed 32 bits), write a ...
- LeetCode Power of Three
原题链接在这里:https://leetcode.com/problems/power-of-three/ 与Power of Two类似.检查能否被3整除,然后整除,再重复检查结果. Time Co ...
随机推荐
- 在后台对GameObject进行"创建"||"删除"动作
在后台对GameObject进行"创建"||"删除"动作 建立 public GameObject Pre;//在编辑器中用来绑定的Prefabs public ...
- 拥抱ARM妹子 序章!ARM妹子~~ 哥我来啦!
一个负心汉即将移情别恋,从51转到ARM妹子啦?其实8是的,俺准备开后宫.哇——咔~咔~~.考虑功耗和成本等问题,只有51肯定是不够的,所以嘛~~(一脸坏笑)嘿嘿~~,ARM妹子俺追定了.出于对ARM ...
- CentOS 6.5 安装与配置LAMP
准备工作: 1.配置防火墙,开启80端口.3306端口vi /etc/sysconfig/iptables-A INPUT -m state --state NEW -m tcp -p tcp --d ...
- 黑马程序员 c#单态的设计模式 (专题二)
<a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IO开发S</a> ...
- 微软职位内部推荐-Sr DEV Lead, Bing Search Relevance
微软近期Open的职位: Contact Person: Winnie Wei (wiwe@microsoft.com )Sr DEV Lead, Bing Search RelevanceLocat ...
- 3140:[HNOI2013]消毒 - BZOJ
题目描述 Description 最近在生物实验室工作的小 T 遇到了大麻烦. 由于实验室最近升级的缘故,他的分格实验皿是一个长方体,其尺寸为 a*b*c,a.b.c均为正整数.为了实验的方便,它被划 ...
- linux 使用文本编辑器编写shell脚本执行权限不够
在linux下,自己编写的脚本需要执行的时候,需要加上执行的权限 解决方式:chmod 777 test.sh
- [矩阵快速幂]HDOJ4565 So Easy!
题意:给a, b, n, m 求 $\left \lceil ( a+ \sqrt b )^n \right \rceil$ % m 看到 $( a+ \sqrt b )^n$ 虽然很好联想到共轭 但 ...
- Servlet课程0424(一) 通过实现Servlet接口来开发Servlet
//这是我的第一个Servlet,使用实现Servlet接口的方式来开发 package com.tsinghua; import javax.servlet.*; import java.io.*; ...
- Mysql一主多从和读写分离配置简记
近期开发的系统中使用MySQL作为数据库,由于数据涉及到Money,所以不得不慎重.同时,用户对最大访问量也提出了要求.为了避免Mysql成为性能瓶颈并具备很好的容错能力,特此实现主从热备和读写分离. ...