{ }codelper
한 줄 읽기문자 하나P0161

선반 라벨 확인 글자

창고 선반 라벨에는 영어 글자와 숫자로 된 코드가 적혀 있다. 손으로 옮겨 적은 라벨이라 소문자가 섞여 있고, 빈칸과 '-'가 아무 데나 끼어 있을 수 있다. 첫 줄에 라벨 수 n이 주어지고, 다음 n줄에 라벨이 한 줄에 하나씩 주어진다. 라벨마다 빈칸과 '-'를 모두 빼고 소문자를 대문자로 바꿔 코드를 만든다. 코드의 글자마다 값을 정한다: '0'~'9'는 0~9, 'A'~'Z'는 10~35이다. 코드의 왼쪽에서 i번째(1부터 센다) 글자의 값에 i를 곱해 모두 더하고, 그 합을 36으로 나눈 나머지를 r이라 한다. 확인 글자는 r이 0~9이면 숫자 '0'~'9', r이 10~35이면 'A'~'Z'이다(10은 'A', 35는 'Z'). 라벨마다 코드, '-', 확인 글자를 이어 붙여 한 줄에 출력하라.

입력
첫 줄에 n(1 ≤ n ≤ 1000).
다음 n줄의 라벨은 줄 바꿈을 빼고 1 ~ 80글자이고, 영어 대소문자·숫자·빈칸·'-'로만 되어 있다.
줄 앞뒤에 빈칸이 있을 수 있고, 라벨마다 영어 글자나 숫자가 하나 이상 있다
출력
n줄.
줄마다 "코드-확인글자"
예시 1 · stdin
3
sh-04 b
  q7-X  
9
stdout
SH04B-P
Q7X-V
9-9
main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

두 가지를 견줘요.
① 빈칸이 든 줄을 통째로 읽기: Python input()·sys.stdin.readline(), JS·TS는 한꺼번에 읽어 split("\n"), Java BufferedReader.readLine(), C# Console.ReadLine(), C fgets, C++ std::getline, 크레이콘 콘솔.줄읽기().
C++ cin >> s, Java Scanner.next(), C scanf("%s")는 빈칸에서 끊어서 sh-04 b를 두 개로 읽어요.
수와 줄을 섞어 읽을 때의 함정도 있어요: C scanf("%d"), C++ cin >> n, Java Scanner.nextInt()는 첫 줄 끝의 줄 바꿈을 남겨 두어, 바로 다음 fgets·getline·nextLine()이 빈 줄을 읽어요.
첫 줄도 줄로 읽어 수로 바꾸면 안전해요.
② 글자와 수 오가기: C·C++·Java·C#의 char는 수라서 c - '0', c - 'A' + 10으로 바로 값을 얻어요.
거꾸로 수를 글자로 되돌릴 때 'A' + r - 10은 int라서, Java StringBuilder.append·C# StringBuilder.Append·C++ std::cout <<에 그대로 주면 P 대신 25가 붙어요.
(char)(C++은 static_cast<char>)로 바꿔야 해요.
C printf("%c", ...)는 int를 받아 글자로 찍어요.
Python·JS·TS·크레이콘에는 글자 타입이 없어서 코드로 오가요: Python ord·chr(또는 int(c, 36)이 바로 0~35), JS·TS charCodeAt·String.fromCharCode, 크레이콘 글자.코드·글자.글자로변환.
JS에서 "7" - "0"은 7이지만 글자에는 맞지 않아요: 모든 글자에 charCodeAt(0) - 48을 쓰면 'B'가 11이 아니라 18이 돼요.
그리고 소문자를 대문자로 먼저 바꾸지 않으면 'b' - 'A' + 10은 43이에요.

Pythonmain.py · 22 줄
import sys  def value(c):    # '0'~'9' → 0~9, 'A'~'Z' → 10~35 (글자 코드의 차이로 계산)    if c.isdigit():        return ord(c) - ord("0")    return ord(c) - ord("A") + 10  def check_char(r):    if r < 10:        return chr(ord("0") + r)    return chr(ord("A") + r - 10)  n = int(sys.stdin.readline())for _ in range(n):    line = sys.stdin.readline().rstrip("\n")  # 빈칸이 든 한 줄을 통째로    code = "".join(c.upper() for c in line if c not in " -")    total = sum(value(c) * i for i, c in enumerate(code, 1))    print(f"{code}-{check_char(total % 36)}")
JavaScriptmain.js · 20 줄
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const ZERO = "0".charCodeAt(0);const A = "A".charCodeAt(0); // '0'~'9' → 0~9, 'A'~'Z' → 10~35const value = (c) => {  const k = c.charCodeAt(0);  return k <= "9".charCodeAt(0) ? k - ZERO : k - A + 10;};const checkChar = (r) => String.fromCharCode(r < 10 ? ZERO + r : A + r - 10); const out = [];for (let i = 1; i <= n; i++) {  const code = lines[i].replace(/[ -]/g, "").toUpperCase();  let total = 0;  for (let j = 0; j < code.length; j++) total += value(code[j]) * (j + 1);  out.push(`${code}-${checkChar(total % 36)}`);}console.log(out.join("\n"));
TypeScriptmain.ts · 23 줄
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const ZERO: number = "0".charCodeAt(0);const A: number = "A".charCodeAt(0); // '0'~'9' → 0~9, 'A'~'Z' → 10~35function value(c: string): number {  const k: number = c.charCodeAt(0);  return k <= "9".charCodeAt(0) ? k - ZERO : k - A + 10;}function checkChar(r: number): string {  return String.fromCharCode(r < 10 ? ZERO + r : A + r - 10);} const out: string[] = [];for (let i = 1; i <= n; i++) {  const code: string = lines[i].replace(/[ -]/g, "").toUpperCase();  let total = 0;  for (let j = 0; j < code.length; j++) total += value(code[j]) * (j + 1);  out.push(`${code}-${checkChar(total % 36)}`);}console.log(out.join("\n"));
JavaMain.java · 30 줄
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    // '0'~'9' → 0~9, 'A'~'Z' → 10~35 (char는 수처럼 뺄 수 있다)    static int value(char c) {        return Character.isDigit(c) ? c - '0' : c - 'A' + 10;    }     static char checkChar(int r) {        return r < 10 ? (char) ('0' + r) : (char) ('A' + r - 10); // int → char로 되돌린다    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            String line = in.readLine(); // 빈칸이 든 한 줄을 통째로            StringBuilder code = new StringBuilder();            for (char c : line.toCharArray())                if (c != ' ' && c != '-') code.append(Character.toUpperCase(c));            int total = 0;            for (int j = 0; j < code.length(); j++) total += value(code.charAt(j)) * (j + 1);            out.append(code).append('-').append(checkChar(total % 36)).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 27 줄
using System;using System.Text; class Program{    // '0'~'9' → 0~9, 'A'~'Z' → 10~35 (char끼리 빼면 int)    static int Value(char c) => char.IsDigit(c) ? c - '0' : c - 'A' + 10;     static char CheckChar(int r) => r < 10 ? (char)('0' + r) : (char)('A' + r - 10);     static void Main()    {        int n = int.Parse(Console.ReadLine());        var out_ = new StringBuilder();        for (int i = 0; i < n; i++)        {            string line = Console.ReadLine(); // 빈칸이 든 한 줄을 통째로            var code = new StringBuilder();            foreach (char c in line)                if (c != ' ' && c != '-') code.Append(char.ToUpperInvariant(c));            int total = 0;            for (int j = 0; j < code.Length; j++) total += Value(code[j]) * (j + 1);            out_.Append(code).Append('-').Append(CheckChar(total % 36)).Append('\n');        }        Console.Write(out_);    }}
C++main.cpp · 27 줄
#include <cctype>#include <iostream>#include <string> // '0'~'9' → 0~9, 'A'~'Z' → 10~35int value(char c) {    return std::isdigit(static_cast<unsigned char>(c)) ? c - '0' : c - 'A' + 10;} int main() {    std::string line;    std::getline(std::cin, line);    int n = std::stoi(line); // cin >> n 뒤에 getline을 쓰면 남은 줄 끝을 빈 줄로 읽는다    std::string out;    for (int i = 0; i < n; i++) {        std::getline(std::cin, line); // 빈칸이 든 한 줄을 통째로        std::string code;        for (char c : line)            if (c != ' ' && c != '-') code += static_cast<char>(std::toupper(static_cast<unsigned char>(c)));        int total = 0;        for (std::size_t j = 0; j < code.size(); j++) total += value(code[j]) * static_cast<int>(j + 1);        int r = total % 36;        char check = static_cast<char>(r < 10 ? '0' + r : 'A' + r - 10); // int → char        out += code + '-' + check + '\n';    }    std::cout << out;}
Cmain.c · 26 줄
#include <ctype.h>#include <stdio.h>#include <stdlib.h> /* '0'~'9' → 0~9, 'A'~'Z' → 10~35: C의 char는 작은 정수라 그대로 뺀다 */static int value(char c) {    return isdigit((unsigned char)c) ? c - '0' : c - 'A' + 10;} int main(void) {    char line[128], code[128];    fgets(line, sizeof line, stdin);    int n = atoi(line); /* scanf("%d")를 쓰면 줄 끝 '\n'이 남아 다음 fgets가 빈 줄을 읽는다 */    for (int i = 0; i < n; i++) {        fgets(line, sizeof line, stdin);        int len = 0;        for (char *p = line; *p && *p != '\n'; p++)            if (*p != ' ' && *p != '-') code[len++] = (char)toupper((unsigned char)*p);        code[len] = '\0';        int total = 0;        for (int j = 0; j < len; j++) total += value(code[j]) * (j + 1);        int r = total % 36;        printf("%s-%c\n", code, r < 10 ? '0' + r : 'A' + r - 10);    }    return 0;}
Craykonmain.cray · 39 줄
// '0'~'9' → 0~9, 'A'~'Z' → 10~35값(c){    k = 글자.코드(c);    만약 (k <= 글자.코드("9"))    {        돌려주기 k - 글자.코드("0");    }    돌려주기 k - 글자.코드("A") + 10;} 확인글자(r){    만약 (r < 10)    {        돌려주기 글자.글자로변환(글자.코드("0") + r);    }    돌려주기 글자.글자로변환(글자.코드("A") + r - 10);} n = 콘솔.줄읽기().수로변환();반복 (i = 0; i < n; i++){    줄 = 콘솔.줄읽기().대문자로변환();    코드 = "";    각각 (c 에서 줄)    {        만약 (c != " " && c != "-")        {            코드 = 코드 + c;        }    }    합 = 0;    반복 (j = 0; j < 코드.길이; j++)    {        합 = 합 + 값(코드[j]) * (j + 1);    }    콘솔.쓰기(코드 + "-" + 확인글자(합 % 36));}