【剑指Offer】二进制中1的个数 解题报告(Python)

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

题目描述:

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

Ways

注意啦,不能使用bin(n).count(‘1’)这个做法,因为n是负数时该式子不成立。

可以使用下面的方法:python要使用n & 0xffffffff得到一个数的补码。。我也不懂为什么..

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

可以使用一个mask来表示正在看到的位数,循环32次,那么就得到了每一个位置上是1的个数。

# -*- 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

每次有符合条件的就把整数右移一位

# -*- 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中有几个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

你可能感兴趣的:(【剑指Offer】二进制中1的个数 解题报告(Python))