剑指offer 面试题15(二进制中1的个数) python

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

 

代码(一):

# -*- coding:utf-8 -*-

class Solution:

    def NumberOf1(self, n):

        # write code here

        if n < 0 :

            n = n & 0xffffffff

        n = bin(n)

        length = len(str(n))

        count = 0

        for i in range(length):

            if "1"==str(n)[i]:

                count += 1

        return count

 

 

# -*- coding:utf-8 -*-

class Solution:

    def NumberOf1(self, n):

        # write code here

        return bin(n).replace("0b","").count("1") if n>=0 else bin(2**32+n).replace("0b","").count("1")

代码思路:就是用1去跟每一位进行与运算。比较傻,要一个个与运算。O(n)

 

 

 

代码():

 

# -*- coding:utf-8 -*-

class Solution:

    def NumberOf1(self, n):

        # write code here

        if n<0:

            n = n & 0xffffffff

        cnt = 0

        while n:

            n = n&(n-1)

            cnt += 1

        return cnt

代码思路:用n&(n-1)来消去一个1 能循环多少次就是能消多少个1~

因为如果那个位置本身就是1的话,那么减去一除了最后一位会变以外,其他都不会变 1111-1=1110;如果最后一位是0;则最右的1变为0,它右边的全部都取反一次,左边不变,然后与原本自己作与能恢复,变回只变换了一位的数据。如1000-1=0111  0111&1000=0000  实际上只把其中最右的1变为0而已;所以他能循环多少次就有多少个1.

 

猜你喜欢

转载自blog.csdn.net/chocolate_chuqi/article/details/81335409