2023年5月18日 星期四

5/18 每日一題 位元運算

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


Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

 

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

 

Constraints:

  • The input must be a binary string of length 32.

 

Follow up: If this function is called many times, how would you optimize it?

這題採用的是無符號整數的二進制表示形式,他跟一般的二進制最大差別在於取消符號位,
所有位數都用來表示數值, 
也就是說 一般的8位數二進制, 他最高位數是符號位 剩下7位才表示數值(-128到127)
無符號則是0到255
p.s 二進制,用最高位數表示負數,其餘表示絕對值,對於8位二進制數,最高位為1表示負數,其餘7位表示絕對值
其中絕對值得範圍是從0 到 2**(n-1)-1 , 也就是0到127
最高位數是1時,是負數的最小值即-128 ,而最高位為0時, 即0,是正數的最小值

----------------------------------------------------------
class Solution:
    def hammingWeight(self, n: int) -> int:
        res=0
        while n != 0:
            res += n&1 #如果最低位數是1 就會是+1 如果是0 就是+0
            n>>=1 #最低位數移除(ex: n=1011, n=n>>1 , n=0101)
        return res #回傳的就是每次出現1的次數
--------------------------------------

參考解答


    return bin(number).count('1')

    #bin(number)會將整數number轉換成二進制的字符串,ex:bin(11)='0b1011'
    #然後使用count('1')計算二進制中1的數量







0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁