題目地址: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