首页 > 其他分享 >lintcode: O(1) Check Power of 2

lintcode: O(1) Check Power of 2

时间:2022-12-01 19:07:18浏览次数:34  
标签:return Power MIN INT lintcode integer 0000 false Check


Using O(1) time to check whether an integer n is a power of 2. Example
For n=4, return true;

For n=5, return false;

Challenge O(1) time

思路:如果n是2的幂,则n的二进制表示中只有一个1. 用n&(n-1),如果结果是0则表示只有一个1. 比如:

((4 & 3) == 0)
100 = 4
011 = 3

有两个例外:

  • 排除n==0的情况
  • 排除INT_MIN。注意INT_MIN的二进制表示为1000 0000 0000 0000 0000 0000 0000 0000
class Solution {
public:
/*
* @param n: An integer
* @return: True or false
*/
bool checkPowerOf2(int n) {
// write your code here
if(!n||n==INT_MIN){
return false;
}
return !(n&(n-1));
}
};


标签:return,Power,MIN,INT,lintcode,integer,0000,false,Check
From: https://blog.51cto.com/u_15899184/5903595

相关文章

  • lintcode: Unique Paths
    Arobotislocatedatthetop-leftcornerofamxngrid(marked‘Start’inthediagrambelow).Therobotcanonlymoveeitherdownorrightatanypointint......
  • lintcode:Trailing Zeros
    15:00StartWriteanalgorithmwhichcomputesthenumberoftrailingzerosinnfactorial.Example11!=39916800,sotheoutshouldbe2ChallengeO(logN)time......
  • lintcode:Update Bits
    Giventwo32-bitnumbers,NandM,andtwobitpositions,iandj.WriteamethodtosetallbitsbetweeniandjinNequaltoM(eg,Mbecomesasubstring......
  • lintcode: Fast Power
    Calculatethea^b%bwherea,bandnareall32bitintegers.ExampleFor231%3=2For1001000%1000=0ChallengeO(logn)思路参见我的博客​​幂模运算​​cla......
  • lintcode:Binary Tree Serialization
    Designanalgorithmandwritecodetoserializeanddeserializeabinarytree.Writingthetreetoafileiscalled‘serialization’andreadingbackfromthe......
  • lintcode: N-Queens
    Then-queenspuzzleistheproblemofplacingnqueensonann×nchessboardsuchthatnotwoqueensattackeachother.Givenanintegern,returnalldistincts......
  • lintcode:Permutations
    Givenalistofnumbers,returnallpossiblepermutations.ChallengeDoitwithoutrecursion.1.递归classSolution{public:/***@paramnums:Alistofi......
  • lintcode:Subsets
    Givenasetofdistinctintegers,returnallpossiblesubsets.ChallengeCanyoudoitinbothrecursivelyanditeratively?1.18sclassSolution{public:/**......
  • lintcode: Permutations II
    Givenalistofnumberswithduplicatenumberinit.Findalluniquepermutations.可以见我的博文​​全排列实现​​classSolution{public:/***@paramnu......
  • lintcode: Subsets II
    Givenalistofnumbersthatmayhasduplicatenumbers,returnallpossiblesubsets1.先排序;再按求Subsets一样的做法,只是添加前检查是否已经存在。耗时171mscla......