

비트마스킹 분류에 있는 문제라서 비트마스킹으로 풀어보려고 했는데 모르겠어서 일단은 그냥 구현했다.
package BOJ;
import java.io.*;
public class sol1094 {
static int x;
static int stickCount = 0;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
x = Integer.parseInt(br.readLine());
int exp = 6;
int sum = 0;
while (true) {
int currentStick = 1 << exp; // 현재 막대의 길이 2^exp
if (sum + currentStick <= x) { // 현재 막대를 사용할 수 있다.(이어 붙였을 때 x보다 작거나 같은 경우)
sum += currentStick;
stickCount++;
} else { // 현재 막대를 사용할 수 없으므로 반으로 자른다
exp--;
}
if (sum == x) { // 이어 붙인 막대 총 길이가 x와 같으면
break;
}
}
System.out.println(stickCount);
}
}
원래의 의도대로 비트마스킹을 사용한 풀이
결국 x 길이의 막대는 만들어진다.
따라서, x가 어떤 막대 길이의 조합인지를 체크한다.
64cm 길이의 막대에서 시작해서 반으로 잘라가면, 잘린 막대도 결국 2의 제곱수가 된다.
즉, 이진수로 나타내었을 때 1의 개수를 카운트 해주면 된다.
package BOJ;
import java.io.*;
public class sol1094 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(br.readLine());
int count = 0;
while (x > 0) {
if ((x & 1) == 1) count++; // 하위 비트가 1이면 막대기 하나 필요
x >>= 1; // 오른쪽으로 한 칸 시프트 (다음 비트로 이동)
}
System.out.println(count);
}
}
비트마스킹을 사용하면 더 빨라지는건가요