메모리: 15880 KB, 시간: 124 ms
비트마스킹, 수학
2024년 12월 14일 19:32:48
지민이는 길이가 64cm인 막대를 가지고 있다. 어느 날, 그는 길이가 Xcm인 막대가 가지고 싶어졌다. 지민이는 원래 가지고 있던 막대를 더 작은 막대로 자른다음에, 풀로 붙여서 길이가 Xcm인 막대를 만들려고 한다.
막대를 자르는 가장 쉬운 방법은 절반으로 자르는 것이다. 지민이는 아래와 같은 과정을 거쳐서 막대를 자르려고 한다.
X가 주어졌을 때, 위의 과정을 거친다면, 몇 개의 막대를 풀로 붙여서 Xcm를 만들 수 있는지 구하는 프로그램을 작성하시오.
첫째 줄에 X가 주어진다. X는 64보다 작거나 같은 자연수이다.
문제의 과정을 거친다면, 몇 개의 막대를 풀로 붙여서 Xcm를 만들 수 있는지 출력한다.
문제 풀이
숫자를 2진수로 표현 후 1의 개수를 세면된다.
코드
/**
* Author: nowalex322, Kim HyeonJae
*/
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static StringTokenizer st;
public static void main(String[] args) throws Exception {
new Main().solution();
}
public void solution() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/java/BOJ_1094_막대기/input.txt")));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int X = Integer.parseInt(br.readLine());
int res = Integer.bitCount(X);
// int count = 0;
// while (X > 0) {
// if ((X & 1) == 1) count++;
// X >>= 1;
// }
bw.write(res + "\n");
bw.flush();
bw.close();
br.close();
}
}
/**
* Author: nowalex322, Kim HyeonJae
*/
#include <bits/stdc++.h>
using namespace std;
// #define int long long
#define MOD 1000000007
#define INF LLONG_MAX
#define ALL(v) v.begin(), v.end()
#ifdef LOCAL
#include "algo/debug.h"
#else
#define debug(...) 42
#endif
void solve() {
int x;
cin >> x;
int res = 0;
while (x > 0) {
res += x & 1;
x >>= 1;
}
cout << res << "\n";
// cout << __builtin_popcount(x) << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt = 1; // 기본적으로 1번의 테스트 케이스를 처리
// cin >> tt; // 테스트 케이스 수 입력 (필요 시)
while (tt--) {
solve();
}
return 0;
}