Problem
숫자 n
을 이진수로 변환했을 때 1 비트의 갯수를 구하는 문제입니다.
Solution
시프트 연산을 진행하면서 풀면 됩니다.
주의할 점은 음수도 주어질 수 있기 때문에 >>>
연산을 사용해야 합니다.
Java Code
public class Solution {
public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
sum += (n & 1);
n >>>= 1;
}
return sum;
}
}
Kotlin Code
class Solution {
fun hammingWeight(n:Int):Int = Integer.toBinaryString(n).count { it == '1' }
}
'알고리즘 문제 > LeetCode' 카테고리의 다른 글
[LeetCode Easy] Happy Number (Java) (0) | 2020.12.28 |
---|---|
[LeetCode Easy] Best Time to Buy and Sell Stock (Java) (0) | 2020.12.23 |
[LeetCode Easy] Intersection of Two Arrays II (Java) (0) | 2020.11.26 |
[LeetCode Easy] Missing Number (Java, Kotlin) (0) | 2020.11.26 |
[LeetCode Easy] Employee Importance (Java) (0) | 2020.11.25 |