Post

[LeetCode 191] Number of 1 Bits

LeetCode 191 (Java)
[Number of 1 Bits] 문제 풀이

[LeetCode 191] Number of 1 Bits

문제 바로가기


Description


Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).


Example 1


  • Input: n = 11
  • Output: 3
  • Explanation: The input binary string 1011 has a total of three set bits.


Example 2


  • Input: n = 128
  • Output: 1
  • Explanation: The input binary string 10000000 has a total of one set bit.


Example 3


  • Input: n = 2147483645
  • Output: 30
  • Explanation: The input binary string 1111111111111111111111111111101 has a total of thirty set bits.


Constraints


  • 1 <= n <= 2^31 - 1







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int hammingWeight(int n) {
        int result = 0; // 결과 값 변수

        while (n > 0) {
             result += n % 2;
             n /= 2;
        }
        return result;
    }
}


RuntimeMemory
0 ms40.6 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int hammingWeight(int n) {
        int c=0;
        while(n>0){
            n=n&(n-1);
            c++;
        }
        return c;
    }
}


Reference


This post is licensed under CC BY 4.0 by the author.