Reverse Bits , Number Of 1 Bits

Yohan Kim·2021년 9월 18일
0

problem

reverse bits는 주어진 32bit 인수를 뒤집어서 return 하는 문제이고

number Of 1 bits 는 주어진 인수에서 자리가 1인 비트를 세는 문제이다.

두 문제가 너무 유사해서 한번에 하기로 했다.

https://leetcode.com/problems/reverse-bits/
https://leetcode.com/problems/number-of-1-bits/

solution

Reverse bits

//problem No: 190
class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t ans = n&1;
        for(int i=0;i<31;i++)
        {
            ans <<= 1;
            n >>= 1;
            ans += n&1;
        }
        return ans;
        
    }
};

number of 1 bits

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

후기

주어진 문제 둘 다 비트연산자를 활용하는 문제이다.
and or 에서 bool 연산자를 쓰지 않도록 주의 하도록하자

왜냐하면 bool 연산자를 쓰면,
(bool)로 인수를 바꾸어서 계산하기 때문에 원하는 값이 나오지 않을 것 이다.
ex) 0x111 -> 1 0x110 -> 1 (0이아니면 모두 1)

unit32_t는 32비트의 크기를 가지는 유닛? 이라고 생각하면된다.
unsigned_int와 똑같다고 생각할 수 있다.

profile
안녕하세요 반가워요!

0개의 댓글