首页 > 其他分享 >leetcode 191. Number of 1 Bits

leetcode 191. Number of 1 Bits

时间:2023-05-30 17:34:30浏览次数:51  
标签:count bits into 191 each put Bits leetcode those

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        assert n>=0
        ans = 0
        while n:
            ans += 1
            n = (n-1)&n
        return ans

 

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        assert n>=0
        ans = 0
        while n:
            ans += (n&1)
            n >>= 1
        return ans

 

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        assert n>=0
        return bin(n).count('1')

 

其他解法:

Another several method of O(1) time.

Add 1 by Tree:

// This is a naive implementation, shown for comparison, and to help in understanding the better functions. 
// It uses 24 arithmetic operations (shift, add, and).
int hammingWeight(uint32_t n)
{
    n = (n & 0x55555555) + (n >>  1 & 0x55555555); // put count of each  2 bits into those  2 bits 
    n = (n & 0x33333333) + (n >>  2 & 0x33333333); // put count of each  4 bits into those  4 bits 
    n = (n & 0x0F0F0F0F) + (n >>  4 & 0x0F0F0F0F); // put count of each  8 bits into those  8 bits 
    n = (n & 0x00FF00FF) + (n >>  8 & 0x00FF00FF); // put count of each 16 bits into those 16 bits 
    n = (n & 0x0000FFFF) + (n >> 16 & 0x0000FFFF); // put count of each 32 bits into those 32 bits 
    return n;
}

// This uses fewer arithmetic operations than any other known implementation on machines with slow multiplication.
// It uses 17 arithmetic operations.
int hammingWeight(uint32_t n)
{
    n -= (n >> 1) & 0x55555555; //put count of each 2 bits into those 2 bits
    n = (n & 0x33333333) + (n >> 2 & 0x33333333); //put count of each 4 bits into those 4 bits
    n = (n + (n >> 4)) & 0x0F0F0F0F; //put count of each 8 bits into those 8 bits
    n += n >> 8; // put count of each 16 bits into those 8 bits
    n += n >> 16; // put count of each 32 bits into those 8 bits
    return n & 0xFF;
}

// This uses fewer arithmetic operations than any other known implementation on machines with fast multiplication.
// It uses 12 arithmetic operations, one of which is a multiply.
int hammingWeight(uint32_t n)
{
    n -= (n >> 1) & 0x55555555; // put count of each 2 bits into those 2 bits
    n = (n & 0x33333333) + (n >> 2 & 0x33333333); // put count of each 4 bits into those 4 bits
    n = (n + (n >> 4)) & 0x0F0F0F0F; // put count of each 8 bits into those 8 bits 
    return n * 0x01010101 >> 24; // returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24)
}

——From Wikipedia.

标签:count,bits,into,191,each,put,Bits,leetcode,those
From: https://blog.51cto.com/u_11908275/6381013

相关文章

  • leetcode 326. Power of Three
    Givenaninteger,writeafunctiontodetermineifitisapowerofthree.Followup:Couldyoudoitwithoutusinganyloop/recursion?classSolution(object):defisPowerOfThree(self,n):""":typen:int......
  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • leetcode 27. Remove Element
    Givenanarraynumsandavalueval,removeallinstancesofthatvaluein-placeandreturnthenewlength.Donotallocateextraspaceforanotherarray,youmustdothisbymodifyingtheinputarrayin-placeTheorderofelementscanbechanged.Itdoesn&......
  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • leetcode 836. Rectangle Overlap
    Arectangleis representedasa list[x1,y1,x2,y2],where (x1,y1) arethecoordinatesofitsbottom-leftcorner,and(x2, y2) arethecoordinatesofitstop-rightcorner.Tworectanglesoverlapiftheareaoftheirintersectionispositive. Tobecl......
  • leetcode 342. Power of Four
    Givenaninteger(signed32bits),writeafunctiontocheckwhetheritisapowerof4.Example:Givennum=16,returntrue.Givennum=5,returnfalse.Followup:Couldyousolveitwithoutloops/recursion?解法1,经典的数学解法:classSolution(object):def......
  • leetcode 345. Reverse Vowels of a String
    Writeafunctionthattakesastringasinputandreverseonlythevowelsofastring.Example1:Givens="hello",return"holle".Example2:Givens="leetcode",return"leotcede".Note:Thevowelsdoesnotincl......
  • leetcode Most Common Word——就是在考察自己实现split
    819.MostCommonWordGivenaparagraph andalistofbannedwords,returnthemostfrequentwordthatisnotinthelistofbannedwords. Itisguaranteedthereisatleastonewordthatisn'tbanned,andthattheanswerisunique.Wordsinthelist......
  • leetcode Kth Largest Element in a Stream——要熟悉heapq使用
    703.KthLargestElementinaStreamEasyDesignaclasstofind thekthlargestelementinastream.Notethatitisthekthlargestelementinthesortedorder,notthekthdistinctelement.Your KthLargest classwillhaveaconstructorwhichacceptsanin......
  • leetcode 2712. 使所有字符相等的最小成本
    2712.使所有字符相等的最小成本给你一个下标从 0 开始、长度为 n 的二进制字符串 s ,你可以对其执行两种操作:选中一个下标 i 并且反转从下标 0 到下标 i(包括下标 0 和下标 i )的所有字符,成本为 i+1 。选中一个下标 i 并且反转从下标 i 到下标 n-......