백준 ISBN

KIMYEONGJUN·2025년 1월 1일
0
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

The International Standard Book Number (ISBN) is a 13-digit code for identifying books. These numbers have a special property for detecting whether the number was written correctly.
The 1-3-sum of a 13-digit number is calculated by multiplying the digits alternately by 1’s and 3’s (see example) and then adding the results. For example, to compute the 1-3-sum of the number 9780921418948 we add
9 ∗ 1 + 7 ∗ 3 + 8 ∗ 1 + 0 ∗ 3 + 9 ∗ 1 + 2 ∗ 3 + 1 ∗ 1 + 4 ∗ 3 + 1 ∗ 1 + 8 ∗ 3 + 9 ∗ 1 + 4 ∗ 3 + 8 ∗ 1
to get 120.
The special property of an ISBN number is that its 1-3-sum is always a multiple of 10.
Write a program to compute the 1-3-sum of a 13-digit number. To reduce the amount of typing, you may assume that the first ten digits will always be 9780921418, like the example above. Your program should input the last three digits and then print its 1-3-sum. Use a format similar to the samples below.

내가 이 문제를 보고 생각해본 부분

정적 변수: ISBN이라는 문자열 변수를 선언하고, 초기값으로 "9780921418"이라는 10자리 ISBN 문자열을 설정해준다.
BufferedReader: InputStreamReader를 사용하여 표준 입력을 읽기 위한 BufferedReader 객체를 만들어준다.
1-3 합 계산:
합계 초기화: sum 변수를 0으로 초기화해준다.
for 루프: ISBN 문자열의 각 자리수를 반복하여 처리해준다.
가중치 계산: 인덱스가 짝수일 때는 1을 곱하고, 홀수일 때는 3을 곱하여 sum에 추가해준다.
사용자 입력 처리:
사용자 입력: 3개의 숫자를 입력받기 위한 루프이다.
가중치 계산: 입력받은 숫자에 대해서도 인덱스에 따라 1 또는 3을 곱하여 sum에 추가한다.
출력: 최종 계산된 1-3합계를 출력한다.

코드로 구현

package baekjoon.baekjoon_25;

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

// 백준 6810번 문제
public class Main886 {
    static String ISBN = "9780921418";

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int sum = 0;
        // 첫 10자리의 weighted sum 계산
        for(int i = 0; i < ISBN.length(); i++) {
            // 1, 3 alternate weight 설정
            if(i % 2 == 0) {
                sum += Integer.parseInt(String.valueOf(ISBN.charAt(i))) * 1;
            } else {
                sum += Integer.parseInt(String.valueOf(ISBN.charAt(i))) * 3;
            }
        }

        // 사용자로부터 3자리 입력받기
        for(int i = 0; i < 3; i++) {
            int inputDigit = Integer.parseInt(br.readLine());
            // 1, 3 alternate weight 설정
            if(i % 2 == 0) {
                sum += inputDigit * 1;
            } else {
                sum += inputDigit * 3;
            }
        }

        System.out.println("The 1-3-sum is " + sum);
        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글

관련 채용 정보