[C++] 백준 1094번 막대기

xyzw·2025년 3월 14일
0

algorithm

목록 보기
53/61

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

풀이

x를 이진수로 나타냈을 때 1의 개수를 출력하면 된다.

x와 1, 10, ... , 1000000을 & 연산했을 때 참이면, 해당 자리에 1이 있다는 것이므로 구하고자 하는 1의 개수가 +1 된다.

코드

#include <iostream>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    
    int x, ans=0;
    cin >> x;
    for(int i=0; i<=6; i++) {
        if(x & (1 << i)) ans++;
    }
    cout << ans;
    
    return 0;
}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN