-
191. Number of 1 Bits javaLeetCode_Study_Plan/Programming Skills 2022. 9. 19. 20:48
https://leetcode.com/problems/number-of-1-bits/
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'LeetCode_Study_Plan > Programming Skills' 카테고리의 다른 글
976. Largest Perimeter Triangle java (0) 2022.09.19 1281. Subtract the Product and Sum of Digits of an Integer java (0) 2022.09.19 1491. Average Salary Excluding the Minimum and Maximum Salary python java (1) 2022.09.19 1523. Count Odd Numbers in an Interval Range python java (1) 2022.09.19 [Programming Skills I] 시작 그리고 도전 (0) 2022.09.19