題目:給定一個(gè)整數(shù)展父,輸出這個(gè)整數(shù)的二進(jìn)制表示中1的個(gè)數(shù)。例如:給定整數(shù)7玲昧,其二進(jìn)制表示為111栖茉,結(jié)果為3。
分析:
(1)移位法孵延。位操作吕漂。首先,判斷這個(gè)數(shù)的最后以為是否為1隙袁,如果為1痰娱,那么計(jì)算器加1弃榨,然后通過(guò)右移丟棄掉最后一位,循環(huán)執(zhí)行該操作直到這個(gè)數(shù)等于0位置梨睁。在判斷二進(jìn)制表示的最后一位是否為1時(shí)鲸睛,可以采用與運(yùn)算來(lái)達(dá)到這個(gè)目的。
code1:
def countOnes1(x):
? ? count = 0
? ? while x > 0:
? ? ? ? if x & 1 == 1:? # 判斷最后一位是否為1
? ? ? ? ? ? count += 1
? ? ? ? x >>= 1? # 移位丟掉最后一位
? ? return count
c = countOnes1(x)
print("binary from of 1234 is {0}".format(bin(x)))
print("binary from of 1234 is {0}".format(c))
(2)與操作坡贺。給定一個(gè)數(shù)n官辈,每進(jìn)行一次n&(n-1)計(jì)算,其結(jié)果中都會(huì)少了一位1遍坟,而且是最后一位拳亿。
code:
def countOnes2(x):
? ? count = 0
? ? while x > 0:
? ? ? ? count += 1
? ? ? ? x &= (x - 1)
? ? return count
x = 1234
c = countOnes2(x)
print("binary from of 1234 is {0}".format(bin(x)))
print("binary from of 1234 is {0}".format(c))