題目描述
輸入一個整數(shù),輸出該數(shù)二進制表示中1的個數(shù)。其中負數(shù)用補碼表示。
思路
- 一個數(shù)n與n-1按位與后,該數(shù)最右邊的1變?yōu)?
- 在python中int是無精度的,所以負數(shù)補碼左邊有無限個1,需要轉換
Code
- Python
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
return bin(n).count("1") if n>=0 else bin(2**32+n).count("1")
- JavaScript
function NumberOf1(n)
{
let count = 0
while(n!= 0){
count += 1
n = n & (n - 1)
}
return count
}