[백준] 11145번 Is it a Number? Java 문제 풀이

2022. 2. 7. 12:41알고리즘/백준

728x90
반응형

문제풀이

import java.io.*;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

interface Main{
    static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int T = Integer.parseInt(br.readLine());
        String regex = "^[\\s]*([\\d]+)[\\s]*$";
        String str = "";
        Matcher matcher;
        for(int i=0; i<T; i++) {
          str = br.readLine();
          matcher = Pattern.compile(regex).matcher(str);
          if(matcher.find()) {
            bw.write(new BigDecimal(matcher.group(1)) + "\n");
          } else {
            bw.write("invalid input\n");
          }
        }        
        bw.flush(); 
      }
}

단일 입력된 자연수만 허용되므로 소수, 음수, 여러 숫자 입력 등은 모두 invalid input을 출력합니다.

 

입력받은 숫자 앞뒤로 공백이 허용되므로 정규식에 추가했습니다.

 

출처 : https://www.acmicpc.net/problem/11145

 

11145번: Is it a Number?

This is it! You’ve finally graduated and started working. Looking forward to some really cool tasks now. While you’re skipping around in the eagerness of getting started, you’re told what your first task is - Input Validation! You should check whethe

www.acmicpc.net

 

728x90
반응형