题目:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2
解法:
#!/usr/bin/pythondef NumberOf1(n): count = 0 while n: if n & 1: count += 1 n = n >> 1 return countdef NunberOf1A(n): count = 0 while n: count += 1 n = (n-1) & n return count# different from c, it won't stop correctlydef NumberOf1B(n): count = 0 flag = 1 while flag: if n & flag: count += 1 flag = flag << 1 return countdef main(): number = 9 print NumberOf1(number) print NunberOf1A(number) print NumberOf1B(number) if __name__ == '__main__': main()