[백준 알고리즘] 3460번 / 이진수

2021. 7. 24. 23:24알고리즘/백준

728x90
반응형
SMALL

문제

양의 정수 n이 주어졌을 때, 이를 이진수로 나타냈을 때 1의 위치를 모두 찾는 프로그램을 작성하시오.

최하위 비트(least significant bit, lsb)의 위치는 0이다.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다.

각 테스트 케이스는 한 줄로 이루어져 있고, n이 주어진다. (1 ≤ T ≤ 10, 1 ≤ n ≤ 106)

 

출력

각 테스트 케이스에 대해서, 1의 위치를 공백으로 구분해서 줄 하나에 출력한다. 위치가 낮은 것부터 출력한다.

 

입출력 예제

입력 출력
1
13
0 2 3

 

 

🌈 문제 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
 
public class No3460_Binary {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int t = sc.nextInt();
        
        for (int i = 0; i < t; i++) {
            int n = sc.nextInt();
            
            String binary = Integer.toBinaryString(n);
            List<Integer> list = new ArrayList<Integer>();
            
            for (int j = 0; j < binary.length(); j++) {
                list.add(Integer.parseInt(binary.substring(j, j+1)));
            }
 
            Collections.reverse(list);
            
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j) == 1) {
                    System.out.print(j + " ");
                }
            }
            System.out.println();
        }
        
        sc.close();
    }
}
 
cs

 

👩‍💻 풀어보기 👨‍💻 https://www.acmicpc.net/problem/3460

 

3460번: 이진수

양의 정수 n이 주어졌을 때, 이를 이진수로 나타냈을 때 1의 위치를 모두 찾는 프로그램을 작성하시오. 최하위 비트(least significant bit, lsb)의 위치는 0이다.

www.acmicpc.net

 

728x90
반응형
LIST