본문 바로가기

백준 문제풀이/Bitmask

[C++] 백준 문제풀이 (Bitmask) 24389 2의 보수

 

https://www.acmicpc.net/problem/24389

 

 

#include <bits/stdc++.h>


int main()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n, ans = 0;
    std::cin >> n;

    int flag = 1;
    // 원래 수와 그 수의 2의 보수를 XOR연산을 하면 서로 다른비트 부분만 남게된다.
    n =  n ^ (~n + 1);

    // 1을 왼쪽으로 쉬프트하면서 1인 비트를 카운팅
    for (int i = 0; i < 32; ++i){
        if (n & flag) ++ans;
        flag <<= 1;
    }
    std::cout << ans << "\n";
    return 0;
}