본문 바로가기

Programming/알고리즘

[백준] 2588번 - 곱셈 - JAVA[자바]

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



public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int a = Integer.parseInt(br.readLine());
        int b = Integer.parseInt(br.readLine());
        
        br.close();
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(a * (b%10));
        sb.append("\n");
        
        sb.append(a * ((b/10)%10));
        sb.append("\n");
        
        sb.append(a * (b/100));
        sb.append("\n");
        
        sb.append(a * b);
                       
        System.out.print(sb);
        
    }
}

위와같이 연산을 이용하면 쉽다.

 

 

하지만 문자열로 입력받아 charAt()로 하나씩 꺼내 쓰는 방법도 있다.

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

public class Main {
 
	public static void main(String[] args) {
		BufferdReader br = new BufferedReader(new InputStreamReader(System.in));
 		int a = Integer.parseInt(br.readLine());
		String B = br.readLine();
        
		br.close();
 
		System.out.println(A * (B.charAt(2) - '0'));
		System.out.println(A * (B.charAt(1) - '0'));
		System.out.println(A * (B.charAt(0) - '0'));
		System.out.println(A * Integer.parseInt(B));
 
	}
}

A는 int, B는 String 으로 입력받고, 

B는 charAt()으로 각 자리수를 참조해준다. 

 

뒤에 -'0'을 해주는 이유는 우리가 문자열 인덱스를 사용하기 위해 B를 String으로 선언하였지만,
문자로 저장된 숫자(아스키 코드)가 아닌 숫ㄱ자 그대로를 정수로 쓰기 위함이다.

 

 


한편, 

 

위의 것이 BufferedReader를 닫아주는 br.close(); 를 쓰지 않은 것인데, 더 빠르게 나온 이유는
데이터의 크기가 크지 않아서 실행하는 로직 자체가 더 오래 걸리기 때문인 것 같다.