본문 바로가기
Algorithm/LeetCode

[LeetCode] 191 | Number of 1 Bits

by 밤초록 2022. 5. 24.
191 | Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/

 

 

 

작성 코드

 

 

접근 방법

 

  • string 형으로 변환 후 1을 count

 

class Solution:
    def hammingWeight(self, n: int) -> int:
        return(bin(n).count("1"))

 

 

  • str(n)으로 설정하니 00000000000000000000000000001011 -> 11 으로 변환되었음,n 자체는 10진수
  • bin() 함수를 이용하여 10진수를 2진수로 변환

 

 

추가 코드

 

비트 연산을 이용한 정석적인 풀이

 

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n > 0) {
            count++;
            n = n & (n - 1);
        }
        return count;
        
    }
};

 

  • & (and) 연산을 이용하여 n & (n - 1) 연산 수행
  • n > 0  일 때, 즉 n을 2진수로 변환하였을 때 1이 하나라도 있을 때까지 while 문 수행, count ++

 

00000000000000000000000000001011 // input

// 첫번째 반복
00000000000000000000000000001011 // bitset<32>(n)
00000000000000000000000000001010 // bitset<32>(n - 1)
00000000000000000000000000001010 // bitset<32>(n) & bitset<32>(n - 1)

// 2번째 반복
00000000000000000000000000001010 // bitset<32>(n)
00000000000000000000000000001001 // bitset<32>(n - 1
00000000000000000000000000001000 // bitset<32>(n) & bitset<32>(n - 1)

// 3번째 반복
00000000000000000000000000001000 // bitset<32>(n)
00000000000000000000000000000111 // bitset<32>(n - 1
00000000000000000000000000000000 // bitset<32>(n) & bitset<32>(n - 1)

// n > 0 이 아니므로 반복문 종료

 

 


 

 

c++ 에서의 내장함수 이용

 

 

class Solution {
public:
    int hammingWeight(uint32_t n) {
        return bitset<32>(n).count();
    }
};

 

  • count() 함수는 bitset 에서 true(1)인 비트 수를 반환
반응형

댓글