【劍指Offer】二進(jìn)制中1的個(gè)數(shù) 解題報(bào)告(Python)

題目地址:https://www.nowcoder.com/ta/coding-interviews

題目描述:

輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示。

Ways

注意啦,不能使用bin(n).count(‘1’)這個(gè)做法,因?yàn)閚是負(fù)數(shù)時(shí)該式子不成立。

可以使用下面的方法:python要使用n & 0xffffffff得到一個(gè)數(shù)的補(bǔ)碼。。我也不懂為什么..

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        cnt = 0
        if n < 0:
            n = n & 0xffffffff
        return bin(n).count('1')

可以使用一個(gè)mask來表示正在看到的位數(shù),循環(huán)32次,那么就得到了每一個(gè)位置上是1的個(gè)數(shù)。

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        mask = 1
        cnt = 0
        for i in range(32):
            if n & mask:
                cnt += 1
            mask <<= 1
        return cnt

每次有符合條件的就把整數(shù)右移一位

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        count=0;
        for i in range(0,32):
            if n&1:
                count=count+1
            n=n>>1
        return count

本題最快的解法是使用n & (n - 1)消去n最后一位的1.消了幾次就是n中有幾個(gè)1.

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        cnt = 0
        if n < 0:
            n = n & 0xffffffff
        while n:
            n =  n & (n - 1)
            cnt += 1
        return cnt
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容