본문 바로가기
공부/알고리즘

코드트리 - 완전탐색, 문자열, 기본

by Austin-Choi 2026. 5. 10.
import java.util.*;
import java.io.*;

/*
제일 앞에있는 0 찾아서 1로 바꾸고 그거 Integer로 출력
*/

public class Main {

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in = br.readLine();
        char[] temp = in.toCharArray();
        int idx = -1;
        for(int i = 0; i<temp.length; i++){
            if(temp[i] == '0'){
                idx = i;
                break;
            }
        }

        // 전부 1일때는 가장 뒤에서 0으로 바꿈
        if(idx == -1){
            System.out.print(Integer.parseInt(in, 2)-1);
        }
        else{
            temp[idx] = '1';
            System.out.print(Integer.parseInt(new String(temp), 2));
        }
    }
}

 

정리

 이상의 정수  진법으로 나타낸 뒤, 그 숫자들 중 정확히 한 숫자만을 바꾼 숫자 가 주어졌을 때, 가능한 숫자  중 최댓값을 찾는 프로그램을 작성해보세요.

풀이

String -> Integer 

Integer.parseInt(str, 2)

Integer -> String

Integer.toBinaryString 인데 문제에서 알고 보니까 그냥 2진수 문자열이 처음 입력으로 등장해서 필요 없었다.