백준/Java

[백준 자바] 3460번(이진수) - '1' 위치 찾기

gamzaggang7 2024. 6. 19. 21:41
728x90

난이도 - 브론즈 3

문제

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

입력

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

출력

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

 


 

728x90

2진수로 바꾸는 과정에서 n%2가 0이 나올 때마다 그 위치(index)를 저장한다.

import java.io.*;

public class Main3460 {
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

    int T = Integer.parseInt(br.readLine());

    while (T-- > 0) {
      int n = Integer.parseInt(br.readLine());
      bw.write(toFindBinaryOne(n) + '\n');
    }

    bw.flush();
    br.close();
    bw.close();
  }

  static String toFindBinaryOne(int n) {
    StringBuffer result = new StringBuffer();

    int index = 0;
    do {
      if (n % 2 == 1)
        result.append(index).append(' ');

      n /= 2;
      index++;
    } while (n > 0);

    return result.toString();
  }
}

728x90