백준 Is it a Number?

KIMYEONGJUN·6일 전
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

The first line of input contains a single number T, the number of test cases to follow.
Then follow a single line for each test case; the input to be validated.
0 < T ≤ 500
Each test case will consist of at least 1 and at most 50 characters (excluding the line break).
A test case can contain any character with an ASCII value between 32 and 126 (inclusive).
There should be no leading zeros in the output.

For each test case, output a line containing the value of the number if the input is a valid integer number, or invalid input (all lowercase) if the input is not.

내가 이 문제를 보고 생각해본 부분

BufferedReader를 이용해 입력을 읽는다.
첫 줄에서 테스트 케이스 수 T를 읽고, 반복문으로 각 테스트 케이스를 처리한다.
각 줄을 읽고 trim()으로 앞뒤 공백을 제거한다.
빈 문자열이면 바로 "invalid input"을 출력한다.
정규식 \\d+를 사용해 문자열 전체가 숫자로만 이루어졌는지 검사한다. 
만약 숫자가 아니면 "invalid input"이다.
숫자 앞에 0이 여러 개 붙어 있다면, 단 한 개의 0만 남기고 앞의 0들은 제거한다. (^0+(?!$) 는 문자열 앞의 0들을 찾아서, 문자열 전체가 0일 경우는 제외)
최종적으로 정제된 숫자를 출력한다.
br.close();를 호출하여 입출력 객체를 닫아 자원을 해제한다.

코드로 구현

package baekjoon.baekjoon_32;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 백준 11145번 문제
public class Main1290 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for(int i = 0; i < T; i++) {
            String input = br.readLine().trim();

            // 유효성 검사: 공백 제거 후 전체가 숫자인지 체크
            if (input.isEmpty() || !input.matches("\\d+")) {
                System.out.println("invalid input");
                continue;
            }

            // 0이 아닌 숫자 앞의 불필요한 0 제거
            input = input.replaceFirst("^0+(?!$)", "");
            System.out.println(input);
        }

        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글