1. 程式人生 > >劍指offer66題--Java實現,c++實現和python實現 11.二進位制中1的個數

劍指offer66題--Java實現,c++實現和python實現 11.二進位制中1的個數

題目描述

輸入一個整數,輸出該數二進位制表示中1的個數。其中負數用補碼錶示。

Python實現

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        cnt = 0
        if n < 0:
            n = n & 0xffffffff
        return bin(n).count('1')
        # write code here

Java實現

public class Solution {
    public int NumberOf1(int n) 
    {
        int count = 0;
                while (n != 0) 
                {
                    ++count;
                    n = (n - 1) & n;
                }
                return count;
    }
}

C++實現

class Solution {
public:
     int  NumberOf1(int n) {
          int count=0;
                 for(int i=0;i<32;i++){
                    if(n>>i&1)  
                        count++;  
                 }
                 return count; 
             }
};