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;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 202 - Happy Number (0) | 2020.12.02 |
---|---|
[JAVA] LeetCode 121 - Best Time to Buy and Sell Stock (0) | 2020.12.02 |
[JAVA] LeetCode 350 - Intersection of Two Arrays II (0) | 2020.12.01 |
[JAVA] LeetCode 268 - Missing Number (0) | 2020.11.30 |
[JAVA] LeetCode 387 - First Unique Character in a String (0) | 2020.11.30 |