1. 程式人生 > >CodeWar----求正整數二進制表示中1的個數

CodeWar----求正整數二進制表示中1的個數

can input tco ber represent n) binary present 因此

Codewars


    Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
    Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
編寫一個以整數作為輸入的函數,並返回該數字的二進制表示中等於1的位數。您可以保證輸入是非負的。

示例:1234is 的二進制表示10011010010,因此在這種情況下函數應該返回5

我的代碼
public class BitCounting {
    public static int countBits(int n){
        // Show me the code!
        int count = 0;
        while(n != 0){
            if((n & 1) == 1){
                count++;
            }
            n = n>>>1;
        }
        return count;
  }
}

最佳代碼
public class BitCounting {
     public static int countBits(int n){
       return Integer.bitCount(n);
     }  
   }

總結
對Java中已實現的功能及其不熟悉

CodeWar----求正整數二進制表示中1的個數