백준 2588 - 곱셈

GwanMtCat·2023년 7월 4일
0

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


내 답

import java.util.Scanner;

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

        int A = sc.nextInt();
        String B = sc.next();

        int firstResult = A * Integer.parseInt(String.valueOf(B.charAt(2)));
        int secondResult = A * Integer.parseInt(String.valueOf(B.charAt(1)));
        int thirdResult = A * Integer.parseInt(String.valueOf(B.charAt(0)));
        int result = firstResult + secondResult * 10 + thirdResult * 100;

        System.out.println(firstResult);
        System.out.println(secondResult);
        System.out.println(thirdResult);
        System.out.println(result);

        sc.close();
    }
}

가능한 다른 풀이방법

String.charAt을 사용할 때 리턴 값은 char 가 나오는데 이 값을 그대로 사용하면 아스키 코드 값이 출력이 된다. (참고로 아스키 코드로 1에서 9는 49에서 57까지다)

여기서 char '0' 을 빼서 형변환 시키면 원래 숫자가 나오게 된다. 주의 할점은 아래 식에서 소괄호() 쳐주지 않으면 정상 출력되지 않는다.

자세한 것은 여기의 설명을 참조하자.

import java.util.Scanner;

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

        int A = sc.nextInt();
        String B = sc.next();

        int firstResult = A * (B.charAt(2) - '0');
        int secondResult = A * (B.charAt(1) - '0');
        int thirdResult = A * (B.charAt(0) - '0');
        int result = firstResult + secondResult * 10 + thirdResult * 100;

        System.out.println(firstResult);
        System.out.println(secondResult);
        System.out.println(thirdResult);
        System.out.println(result);

        sc.close();
    }
}

0개의 댓글