알고리즘

[JAVA] 백준 알고리즘_2588(곱셈)

줌인. 2024. 6. 22. 12:12

▶ 백준 알고리즘 2588

https://www.acmicpc.net/problem/2588

 

 

[문제]

(세 자리 수) × (세 자리 수)는 다음과 같은 과정을 통하여 이루어진다.

(1)과 (2)위치에 들어갈 세 자리 자연수가 주어질 때 (3), (4), (5), (6)위치에 들어갈 값을 구하는 프로그램을 작성하시오.

 

 

[예제 입력]

첫째 줄에 (1)의 위치에 들어갈 세 자리 자연수가, 둘째 줄에 (2)의 위치에 들어갈 세자리 자연수가 주어진다.

472
385

 

 

[예제 출력]

첫째 줄부터 넷째 줄까지 차례대로 (3), (4), (5), (6)에 들어갈 값을 출력한다.

2360
3776
1416
181720

 

 

[제출 코드]

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int b = sc.nextInt();
    int first = (int) (b * 0.01) ;
    int second = (int) (b * 0.1);
    int result1 = a * (b - (first * 100) - (second - (first*10))*10);
    int result2 = a * (second - (first*10));
    int result3 = a * (first);
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result1 + (result2 * 10) + (result3 * 100));

    }
}

- 소수점 연산을 사용한 후 정수 변환을 하기 때문에 정확하지 않음

- b의 각 자릿수를 정확히 분리하지 않음

- first와 second가 부정확하게 계산되었기 때문에 결과도 부정확

 

 

[수정 코드]

▶ https://st-lab.tistory.com/20

아이디어 참고

 

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

https://www.acmicpc.net/problem/2588 2588번: 곱셈 첫째 줄부터 넷째 줄까지 차례대로 (3), (4), (5), (6)에 들어갈 값을 출력한다. www.acmicpc.net 문제 매우 간단한 문제다! 3개의 풀이 방법을 제시한다. 이 문제는

st-lab.tistory.com

 

① CharAT 사용

public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        String num2 = sc.next();

        System.out.println(num1 * Integer.parseInt(num2.charAt(2) + ""));
        System.out.println(num1 *  Integer.parseInt(num2.charAt(1) + ""));
        System.out.println(num1 *  Integer.parseInt(num2.charAt(0) + ""));
        System.out.println(num1 * Integer.parseInt(num2 + ""));
    }
}

- char 타입을 String 타입으로 변환하기 위해 빈 문자열 ("")을 더함

- Integer.parseInt 메서드가 String 타입의 인수를 필요로 하기 때문

 

② 연산자 사용

public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();

        System.out.println(num1 * (num2%10));
        System.out.println(num1 * (num2%100/10));
        System.out.println(num1 * (num2/100));
        System.out.println(num1 * num2);

    }
}

- num2에 385가 들어간다고 가정했을 때

  첫번째 줄 : 5

  두번째 줄 : 85 -> 10으로 나누면 int형이기 때문에 8만 남음

  세번째 줄 : 3 

 

728x90