본문 바로가기

알고리즘/LeetCode

[JAVA] LeetCode 191 - Number of 1 Bits

Write a function that takes an unsigned integer

and returns the number of '1' bits it has (also known as the Hamming weight).

 

부호 없는 정수가 가지는 1 비트 수를 반환하는 함수를 작성하라

(Hamming Weight 이라고도 함)

 

 

# Hamming Weight 이라는 알고리즘이 생소해 구글링을 해보니

2진수로 바꾸었을 때 길이가 n인 정수에서 1인 bit만 세어보는 알고리즘 이라고 한다.

 

 

 

 

풀이 방법

n이 0이 아닐 때까지, 비트 연산을 수행하며 카운팅을 수행한다.

 

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