问题描述
对于任意给定的二进制,求出二进制中1的个数,之前在microsoft的电话面试中遇到,现在做个总结,也练下Python
方法一:
从低到高判断每一个元素是否为1,这里是采用依次与1取与的方法
如5的二进制是101,那101与001取与,结果是001,不等于0,所以count加1。
101向右移一位为010,010与001取与,结果为0,等于0。
101向右移一位位001,001与001取与,结果为001,不等于0,所以count加1.
#!/usr/bin/python # -*- coding: UTF-8 -*- # Author : Mission def bitCount(n): c = 0 #count while n > 0: if n & 1 == 1: #current bit is 1 c += 1 n >>= 1 #move to next bit return c if __name__ == "__main__": n = input("n : ") #input result = bitCount(n) print "the count of one is ", result
方法二(建表法):
上面我们每次判断该位是否为1,再右移一位,现在我们每次计算出4位中1的个数,再右移4位,不过,我们得到4位中,即数字0-15中,1的个数,当然,我们可以每次右移8位,原理是一样的。
#!/usr/bin/python # -*- coding: UTF-8 -*- # Author : Mission def bitCount1(n): table = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] #the count of the first 16 nums c = 0 while n > 0: c += table[n & 0xf] #add the count of 4 low-order bits n >>= 4 #move 4 bits return c if __name__ == "__main__": n = input("n : ") #input result = bitCount1(n) print "the count of one is ", result
方法三(快速法):
第一种最普通的方法得比较32次,第二种方法是第一种方法的改进版,不过前期工作也挺大的,比较次数是大幅度下降,而这种方法是1的个数有几个,就比较几次。
先举个例子,比如14,二进制是1110,而13,二进制是1101,14 & 13的结果是1100,我们要求的是14(1110)中1的个数,现在经过一次运算之后,得到1100,我们消去了14(1110)中最低位的1,而count加一,通过这种方法,当我们14(1110)变成0时,count为3,就是结果。仔细想想也能发现,n-1每次是把n的最低位的1拿出来使用,那再做取与,势必会消去最低位的1。
#!/usr/bin/python # -*- coding: UTF-8 -*- # Author : Mission def bitCount(n): c = 0 #count while n > 0: n &= n - 1 #remove the low-order bit c += 1 return c if __name__ == "__main__": n = input("n : ") #input result = bitCount(n) print "the count of one is ", result