首页 > 其他分享 >lintcode: Flip Bits

lintcode: Flip Bits

时间:2022-12-01 19:07:32浏览次数:43  
标签:XOR return int lintcode Flip ++ num integer Bits


Determine the number of bits required to flip if you want to convert
integer n to integer m.

Example Given n = 31 (11111), m = 14 (01110), return 2.

Note Both n and m are 32-bit integers.

class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/

/*
int num_of_1(int a){
int num = 0;
while (a){
if (a >> 1){
num++;
}
a = a >> 1;
}
return num;
}
*/
//上面程序当a为负数时错误
int num_of_1(int a){
int num=0;

for(int i=0;i<32;i++){
if(a&(1<<i)){
num++;
}
}

return num;
}

int bitSwapRequired(int a, int b) {
// write your code here
int XOR=a^b;
return num_of_1(XOR);
}
};


标签:XOR,return,int,lintcode,Flip,++,num,integer,Bits
From: https://blog.51cto.com/u_15899184/5903594

相关文章

  • lintcode: O(1) Check Power of 2
    UsingO(1)timetocheckwhetheranintegernisapowerof2.ExampleForn=4,returntrue;Forn=5,returnfalse;ChallengeO(1)time思路:如果n是2的幂,则n的二进......
  • 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......