LeetCode_Study_Plan/Programming Skills

191. Number of 1 Bits java

개발하는루루 2022. 9. 19. 20:48

https://leetcode.com/problems/number-of-1-bits/

Number of 1 Bits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        while(n != 0) {
            cnt = cnt + (n & 1); 
            n = n>>>1;
        }
        return cnt;
    }
}

왠지 bit를 카운트해주는 함수도 있을 것 같아 찾아보니 아래와 같은 예시도 있었다.

public int hammingWeight2(int n) {
    return Integer.bitCount(n);
}



참고 : 비트연산 관련
https://staticclass.tistory.com/25