C++版本
class Solution {
public:
int NumberOf1(int n) {
int count=0;
unsigned int flag=1;
while(flag){
if (n & flag){
count++;
}
flag=flag<<1;
}
return count;
}
};
Python版本
# -*- coding:utf-8 -*-
class Solution:
def intToBin32(self, i):
return (bin(((1 << 32) - 1) & i)[2:]).zfill(32)
def NumberOf1(self, n):
# write code here
if n>=0:
return str(bin(n))[2:].count('1')
else:
return (self.intToBin32(n).count('1'))