1 분 소요

image-20231127180451074

문제 출처 https://www.acmicpc.net/problem/2588

백준 2588번은 세 자리 수의 곱을 처리하는 과정에 대한 문제였음.

처음에는 복잡하게 생각해서 로직이 길어졌는데 출력은 맞으나 자꾸 오답처리가 돼서

더 간단한 식으로 바꿔 봄.

몫, 나머지를 다루는 식에 익숙해져야 할 듯

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int A = sc.nextInt();
        int B = sc.nextInt();

        int a = A*(B%10);
        int b = A*((B%100)/10);
        int c = A*(B/100);

        System.out.println(a); // 472 * (385/10의 나머지 5 )
        System.out.println(b); // 472 * (85 / 10) = 472 * 8
        System.out.println(c);
        System.out.println(a + (b*10) + (c*100));
    }
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
    public static void main(String[] args) throws Exception { 
        // 숫자 입력받기
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st1 = new StringTokenizer(br.readLine());
        String[] A = st1.nextToken().split("");
        StringTokenizer st2 = new StringTokenizer(br.readLine());
        String[] B = st2.nextToken().split("");


        // 결과값
        Map<String, List<Integer>> result = new HashMap<String, List<Integer>>();
        int size = B.length-1;

        for (int i = size; i >= 0; i--) { // 2 1 0
            int quotient = 0;
            int remainder = 0;
            List<Integer> mid = new ArrayList<>();
            for (int j = A.length - 1; j >= 0; j--) {

                int b = Integer.parseInt(B[i]);
                int a = Integer.parseInt(A[j]);
                int value = b * a;

                if (quotient != 0) { // 몫이 있다면 value에 누적해서 더해주기
                    value += quotient;
                    quotient = 0; // 초기화
                }

                quotient = value/10; // 몫
                remainder = value%10; // 나머지

                if(j == 0) {
                    mid.add(remainder + (quotient*10));
                    result.put(String.valueOf(i), mid);
                } else {
                    mid.add(remainder);
                }
            }
        }

        List<String> keys = new ArrayList<>(result.keySet());
        Collections.sort(keys, Comparator.reverseOrder());

        int sum = 0;
        int multiplier = 1;

        for (String key : keys) {
            List<Integer> value = result.get(key);
            String resultValue = "";
            for (int i = value.size() - 1; i >= 0; i--) {
                resultValue += value.get(i);
            }
            System.out.println(resultValue);
            sum += Integer.parseInt(resultValue) * multiplier;
            multiplier*=10;
        }
        
        System.out.println(sum);
        
      }
}      

업데이트: