天天看點

劍指offer_【11】二進制中1的個數

1.題目描述

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

2.解題思路

  • 方法1:直接将其轉成二進制數組
  • 方法2:把一個整數減去1,再和原整數做與運算,會把該整數最右邊一個1變成0。那麼一個整數的二進制表示中有多少個1,就可以進行多少次這樣的操作。

3.代碼

方法1:

public class Solution {
    public int NumberOf1(int n) {
        int count=0;
        char []a=Integer.toBinaryString(n).toCharArray();
        for(int i=0;i<a.length;i++)
            {
            if(a[i]=='1')
                {
                 count++;
                }
            }
        return count;
    }
}
           

方法2:

public class Solution {
    public static int NumberOf(int n)

    {
        int count = 0;
        while (n > 0)
        {
            count++;
            n = (n - 1) & n;
        }
        return count;
    }
  }