본문 바로가기

Problem Solving/리트코드

[LeetCode] Number of 1 Bits

비트연산해서 1이 몇 개 있는지 판별하는 코드. 한 번 풀어놓으면 유용하다.

자주 나오지는 않지만 비트연산 나오면 알고 있으면 유용하게 쓰인다고 생각.

비트연산이 잘 안나와 나오기만 하면 죄다 낯설어서 그렇지...

내가 짠 코드

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count =0;
        for(int i=0;i<32;i++){
            if(n&1==1) count ++;
            n = n >> 1;
        }
        return count;
    }
};

leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/

 

'Problem Solving > 리트코드' 카테고리의 다른 글

[LeetCode] Arithmetic SlicesSolution  (0) 2021.02.19
[LeetCode] Linked List Cycle  (0) 2021.02.08
[LeetCode] Squares of a Sorted Array  (0) 2021.01.29
[LeetCode] 541. Reverse String II  (0) 2021.01.27
[LeetCode] 344. Reverse String  (0) 2021.01.27