11번 A+B - 5

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) 

입력의 마지막에는 0 두 개가 들어온다.

 

출력

각 테스트 케이스마다 A+B를 출력한다.

 

이번에는 얼마나 반복할지 횟수를 정해주지 않고 마지막 케이스를 통해 루프를 종료하는 조건으로 사용하면 된다.

 

C++

#include <iostream>
using namespace std;
int main(){
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    while(true){
        int a, b;
        cin >> a >> b;
        if (a + b == 0) break;
        else
            cout << a + b << "\n";
    }
}

 

두 값이 모두 0인 경우 반복문을 종료한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            while(true){
                int a, b;
                string input = Console.ReadLine();
                string[] arr = input.Split(' ');
                a = int.Parse(arr[0]);
                b = int.Parse(arr[1]);
                if (a + b == 0) break;
                else
                    Console.WriteLine(a + b);
            }
        }
    }
}

 

Python

while True:
    input_str = input()
    arr = input_str.split(' ')
    a = int(arr[0])
    b = int(arr[1])
    if a + b == 0:
        break
    print(a + b)

 

파이썬의 while문 사용법을 숙지한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
    const [a, b] = line.split(' ').map(Number);
    if (a + b === 0) break;
    console.log(a + b);
}

 

js는 입력을 한 번에 받은 다음 줄 별로 처리해야 하기 때문에 while이 아닌 for를 사용해서 처리한다.

 

12번 A+B - 4

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 A+B를 출력한다.

 

반복문 챕터의 마지막 문제이다. 종료 조건을 어떠한 것도 주지 않은 상태로 입력이 끝날 때까지 반복하여 처리해야 한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int a, b;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    while(cin >> a >> b){
        if (a + b == 0)
            break;
        cout << a + b << "\n";
    }
    return 0;
}

 

cin >> a >> b를 조건으로 체크하여 입력이 더 이상 없는 경우를 판단한다.

 

조건으로 사용하게 되면 EOF(End of File)에 도달하여 더 이상 입력이 없거나 잘못된 값이 입력된 경우 반복문이 종료된다.

 

using System;
class Program{
    static void Main(string[] args){
        using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            while (true){
                string input = Console.ReadLine();
                if (input == null) break;
                string[] arr = input.Split(' ');
                int a = int.Parse(arr[0]);
                int b = int.Parse(arr[1]);
                Console.WriteLine(a+b);
            }
        }
    }
}


C#에서 string의 초기화값은 null이기 때문에 input이 없는지 확인하기 위해서 null과 비교하여 검사한다.

 

Python

import sys
input = sys.stdin.read
arr = input().splitlines()
for line in arr:
    a, b = map(int, line.split())
    print(a+b)

 

기존 input 함수를 표준 입력으로 변경하여 전체 입력된 정보를 저장한 다음 배열을 읽어서 처리하여 입력된 값들만 처리한다.

 

또 다른 방법으로는 입력이 더 이상 없을 때 발생하는 에러를 체크해서 루프를 종료시킬 수 있다.

 

while True:
    try:
        input_str = input()
    except EOFError:
        break
    arr = input_str.split()
    a = int(arr[0]);
    b = int(arr[1]);
    print(a+b)

 

에러가 발생하는 지점을 예외처리하기 위해서 try ~ except를 사용한다. 입력이 더 이상 없을 때는 EOFError를 리턴한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
    const[a, b] = line.split(' ').map(Number);
    console.log(a+b);
}

 

모든 입력을 줄 바꿈으로 끊어서 배열로 저장한다. 그리고 이 배열을 순회하면서 각각의 케이스를 처리한다.

728x90
반응형

7번 A+B - 7

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력한다. 테스트 케이스 번호는 1부터 시작한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int t;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << "Case #" << i + 1 << ": " << a + b << "\n";
    }
    
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int t = int.Parse(Console.ReadLine());
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
        for (int i = 0; i < t; i++){
            int a, b;
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            a = int.Parse(arr[0]);
            b = int.Parse(arr[1]);
            Console.WriteLine($"Case #{i+1}: {a+b}");
        }
        Console.Out.Flush();
    }
}

 

Python

import sys
t = int(input());
for i in range(t):
    input_str = sys.stdin.readline().rstrip()
    arr = input_str.split(' ');
    a = int(arr[0])
    b = int(arr[1])
    print(f"Case #{i+1}: {a+b}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
const t = parseInt(input[0], 10);
const output = [];
for (let i = 1; i <= t; i++){
    const[a,b] = input[i].split(' ').map(Number);
    output.push(`Case #${i}: ${a+b}`);
}
console.log(output.join('\n'));

 

readFileSync에서 utf8로 명시적으로 인코딩해주지 않으면 반환되는 데이터가 기본적으로 Buffer 객체이므로 문자열 메서드와 함께 사용할 때 에러가 발생할 수 있다.

 

8번 A+B - 8

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 "Case #x: A + B = C" 형식으로 출력한다. x는 테스트 케이스 번호이고 1부터 시작하며, C는 A+B이다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int t;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << "Case #" << i + 1 << ": " << a << " + " << b << " = " << a+b << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int t = int.Parse(Console.ReadLine());
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
        for (int i = 0; i < t; i++){
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            int a = int.Parse(arr[0]);
            int b = int.Parse(arr[1]);
            Console.WriteLine($"Case #{i+1}: {a} + {b} = {a+b}");
        }
        Console.Out.Flush();
    }
}

 

Python

import sys
t = int(input())
for i in range(t):
    input_str = sys.stdin.readline().rstrip()
    arr = input_str.split()
    a = int(arr[0])
    b = int(arr[1])
    print(f"Case #{i+1}: {a} + {b} = {a+b}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const t = parseInt(input[0], 10);
const output = [];
for (let i = 1; i <= t; i++){
    const[a,b] = input[i].split(' ').map(Number);
    output.push(`Case #${i}: ${a} + ${b} = ${a+b}`);
}
console.log(output.join('\n'));

 

7, 8번 문제들은 출력 형식만 다르고 앞에 풀었던 문제와 동일한 방식으로 해결되기 때문에 크게 설명할 내용은 없다.

 

9번 별 찍기 - 1 

문제

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제

 

입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

 

출력

첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.

 

C++

string(size_t count, char ch)를 사용해서 count 만큼 문자를 출력하도록 만들어 본다.

#include <iostream>
#include <string>
using namespace std;
int main() {
    int n;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        string stars(i, '*');
        cout << stars << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        using(StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            for (int i = 1; i <= n; i++){
                string stars = new string('*', i);
                Console.WriteLine(stars);
            }
        }
    }
}

 

C#은 new string(char, count)로 사용이 가능하다. 단일 문자를 반복하는 것이기 때문에 문자열이 아닌 문자를 사용해야 한다는 걸 유의한다.

 

기존 코드를 좀 더 깔끔하게 정리하기 위해서 using을 사용해서 내부에서 동작이 끝나면 자동으로 객체가 해제되도록 한다. 자세히 정리하자면 StreamWriter의 객체의 Dipose 메서드는 내부적으로 Flush를 호출하는데 using을 사용할 경우 객체가 해제될 때 Dispose 메서드가 자동으로 호출되면서 Flush도 처리된다. 따라서 별도로 Flush를 해줄 필요가 없어진다.

 

Python

n = int(input())
for i in range(1, n + 1):
    stars = '*' * i;
    print(stars)

 

파이썬은 문자에 횟수만큼 곱연산을 해서 개수만큼 표기가 가능하다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim();
const count = parseInt(input);
for (let i = 1; i <= count; i++){
    const stars = '*'.repeat(i);
    console.log(stars);
}

 

자바스크립트에서는 char.repeat으로 문자를 개수만큼 입력할 수 있다.

 

10번 별 찍기 - 2

문제

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제

하지만, 오른쪽을 기준으로 정렬한 별(예제 참고)을 출력하시오.

 

입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

 

출력

첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.

 

9번 문제의 변형이다. N만큼 찍힌 별을 기준으로 이전 별들에게 공백이 추가로 필요하며 이 공백은 n - i 개가 된다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++){
        string space(n - i, ' ');
        string stars(i, '*');
        string result = space + stars;
        cout << result << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        using(StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            for (int i = 1; i <= n; i++){
                string space = new string(' ', n - i);
                string stars = new string('*', i);
                string result = space + stars;
                Console.WriteLine(result);
            }     
        }
    }
}

 

Python

n = int(input())
for i in range(1, n+1):
    space = ' ' * (n - i);
    stars = '*' * i;
    result = space + stars;
    print(result);

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim();
const n = parseInt(input);
for (let i = 1; i <= n; i++){
    const space = ' '.repeat(n - i);
    const stars = '*'.repeat(i);
    const result = space + stars;
    console.log(result);
}

 

728x90
반응형

6번 빠른 A+B

문제

본격적으로 for문 문제를 풀기 전에 주의해야 할 점이 있다. 입출력 방식이 느리면 여러 줄을 입력받거나 출력할 때 시간초과가 날 수 있다는 점이다. 

 

C++을 사용하고 있고 cin/cout을 사용하고자 한다면, cin.tie(NULL)과 sync_with_stdio(false)를 둘 다 적용해 주고, endl 대신 개행문자(\n)를 쓰자. 단, 이렇게 하면 더 이상 scanf/printf/puts/getchar/putchar 등 C의 입출력 방식을 사용하면 안 된다. 

 

Java를 사용하고 있다면, Scanner와 System.out.println 대신 BufferedReader와 BufferedWriter를 사용할 수 있다. BufferedWriter.flush는 맨 마지막에 한 번만 하면 된다. 

 

Python을 사용하고 있다면, input 대신 sys.stdin.readline을 사용할 수 있다. 단, 이때는 맨 끝의 개행문자까지 같이 입력받기 때문에 문자열을 저장하고 싶을 경우. rstrip()을 추가로 해 주는 것이 좋다. 

 

또한 입력과 출력 스트림은 별개이므로, 테스트케이스를 전부 입력받아서 저장한 뒤 전부 출력할 필요는 없다. 테스트케이스를 하나 받은 뒤 하나 출력해도 된다. 자세한 설명 및 다른 언어의 경우는 이 글에 설명되어 있다. 이 블로그 글에서 BOJ의 기타 여러 가지 팁을 볼 수 있다.

 

입력

첫 줄에 테스트케이스의 개수 T가 주어진다. T는 최대 1,000,000이다. 다음 T 줄에는 각각 두 정수 A와 B가 주어진다. A와 B는 1 이상, 1,000 이하이다.

 

출력

각 테스트케이스마다 A+B를 한 줄에 하나씩 순서대로 출력한다.

 

입출력 시 발생할 수 있는 문제를 해결하여 테스트케이스를 통과해야 하는 문제이다.

친절하게 문제에서 해결방법을 제시해 주었기 때문에 위 방법들을 고려하여 테스트케이스를 통과해 본다.

 

C++

오답

#include <iostream>
using namespace std;
int main(){
    int t;
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << a + b << "\n";
    }
    return 0;
}

 

확인을 위해 제시된 방법을 사용하지 않고 코드를 작성하여 테스트해 보니 '시간 초과' 결과가 나타난다.

 

위 방법들을 사용해서 다시 풀어본다.

 

#include <iostream>
using namespace std;
int main(){
    int t;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << a + b << "\n";
    }
    return 0;
}

 

cin.tie(NULL)은 cin과 cout의 묶음을 풀어주는 기능을 한다.

기본적으로 cin으로 읽을 때 먼저 출력 버퍼를 비우는 작업이 먼저 처리되는데 이 작업을 통해서 출력이 즉시 화면에 표시되도록 한다. 하지만 이렇게 수만 번의 입력과 출력이 반복해서 처리되는 작업에서는 출력 버퍼를 비우는 작업은 고려하지 않아도 되기 때문에 테스트 케이스를 통과하기 위해서는 이런 부가적인 작업이 발생하지 않도록 해야 타임오버가 되지 않는다.

 

ios_base::sync_with_stdio(false)는 C와 C++의 버퍼를 분리한다.

C++은 C의 기능을 포함하고 있으므로 cin과 cout 사용 시 C의 입출력 라이브러리인 stdin, stdout과 연결된 스트림 객체 상태이다. 따라서 sync_with_stdio(false)를 선언하면 cin/cout은 더 이상 stdin/stdout과 동기화되지 않기 때문에 C++의 스트림 입출력 성능이 향상될 수 있지만 비활성화된 상태에서는 C의 scanf, printf와 함께 사용 시에는 문제가 발생한다.

 

개행문자 endl 은 줄 바꿈을 출력할 뿐만 아니라 출력 버퍼를 비우는 역할까지 하기 때문에 이 작업 역시 테스트케이스를 실행하게 되면 속도를 느리게 하기 때문에 단순 줄 바꿈만 하는 \n 개행문자를 사용하는 것이 속도측면에서 유리하다.

 

C#

C#의 경우 문제에서 해결방법이 제시되지 않아서 추가 정보글의 설명을 먼저 읽어 보았다.

Console.Write, WriteLine은 사용할 때마다 화면으로 내보내는 작업인 flush(C++의 출력버퍼를 비우는 작업)이 발생하는데 해결 방법으로는 StringBuilder에 출력할 내용을 모아둔 뒤 한 번에 출력하거나 auto flush를 하지 않는 output stream을 Console에 연결하는 방법이 있다.

 

StringBuilder

using System;
using System.Text;
class Program{
    static void Main(string[] args){
        StringBuilder sb = new StringBuilder();
        int t = int.Parse(Console.ReadLine());
        for (int i = 0; i < t; i++){
            int a, b;
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            a = int.Parse(arr[0]);
            b = int.Parse(arr[1]);
            sb.AppendLine((a+b).ToString());
        }
        Console.WriteLine(sb.ToString());
    }
}

 

StringBuilder를 사용해서 문자열을 저장하고 한 번에 출력하여 flush로 인한 속도 저하를 방지한다. string이 아닌 StringBuilder를 사용하는 이유는 문자열 연결 작업에서 불변 특성을 가지기 때문에 더 효율적인 처리가 가능하고 string의 문자열을 추가하는 + 연산 작업은 새로운 문자열 객체가 생성되고 이 과정에서 메모리 사용량과 실행 시간이 증가할 수 있다.

 

Append : 문자열만 추가한다.

AppendLine : 문자열 추가하고 줄 바꿈 문자를 자동으로 추가한다.

AppendFormat : 형식 문자열을 추가한다.

 

output stream

using System;
class Program{
    static void Main(string[] args){
        int t = int.Parse(Console.ReadLine());
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
        for (int i = 0; i < t; i++){
            int a, b;
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            a = int.Parse(arr[0]);
            b = int.Parse(arr[1]);
            Console.WriteLine(a + b);
        }
        Console.Out.Flush();
    }
}

 

출력 전 자동으로 flush 하는 기능을 비활성화한다. 이 기능을 사용하고 나서 코드 종료 전에 출력 버퍼를 지우는 Flush()를 호출해 주어야 한다.

 

추가로 StreamReader와 StreamWriter를 사용하는 방법

using System;
using System.IO;

class Program {
    private const int bufferSize = 131072;
    public static readonly StreamReader input = new(new BufferedStream(Console.OpenStandardInput(), bufferSize));
    public static readonly StreamWriter output = new(new BufferedStream(Console.OpenStandardOutput(), bufferSize));

    static void Main(string[] args) {
        int t = int.Parse(input.ReadLine());

        for (int i = 0; i < t; i++) {
            string[] arr = input.ReadLine().Split(' ');
            int a = int.Parse(arr[0]);
            int b = int.Parse(arr[1]);
            output.WriteLine(a + b);
        }
        output.Flush();
    }
}

 

input과 output을 구현하여 처리한다.

마찬가지로 코드가 종료되기 전에 출력버퍼를 비워준다.

 

Python

파이썬에서는 입력을 받는 함수인 input 대신 sys.stdin.readline을 사용하면 된다. 이 경우 문자열 끝에 개행문자까지 같이 입력받게 되므로. rstrip()으로 문자열만 저장하도록 한다.

import sys
t = int(input())
for i in range(t):
    input_str = sys.stdin.readline().rstrip()
    arr = input_str.split(' ');
    a = int(arr[0])
    b = int(arr[1])
    print(a+b)

 

먼저 sys를 사용하기 위해서 모듈을 임포트 해준다.

 

입력받은 문자열을 저장할 때 변수명을 str로 사용했었는데 이 키워드는 파이썬에서 내장 타입으로 사용되고 있기 때문에 문제가 되는 걸 방지하기 위해서 input_str로 사용했다.

 

input을 사용하게 되면 시간초과가 발생한다. 

sys.stdin.readline()은 C 표준 라이브러리의 fgets 함수에 가깝게 동작하는데 이는 입력 스트림에서 한 줄을 읽어오고 문자열로 반환한다. 따라서 직접적으로 표준 입력에서 빠르게 읽어오기 때문에 input보다 더 빠른 속도로 처리할 수 있다.

 

print의 경우 기존 방식을 사용해도 문제가 없다. print 함수는 기본적으로 출력 버퍼링을 사용하긴 하지만 매번 호출할 때마다 버퍼를 flush 하지 않는 게 기본 상태이다. 그리고 이를 수동으로 flush 하도록 변경할 수 있다.

print("Something print", flush=true)

 

Node.js

fs

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const t = parseInt(input[0], 10);
const output = [];

for (let i = 1; i <= t; i++) {
    const [a, b] = input[i].split(' ').map(Number);
    output.push(a + b);
}

process.stdout.write(output.join('\n'));

 

반복문에서 출력할 정보를 저장해 놓고 마지막에 한 번에 출력한다. 

 

위)console.log

 

이때 console.log를 사용해도 성공했는데 process.stdout.write를 사용하는 게 조금 더 빠르게 처리되었다.

 

 

readline

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
let input = [];
let lineIndex = 0;
rl.on('line', (line) => {
    input.push(line);
});
rl.on('close', () => {
    const t = parseInt(input[lineIndex++], 10);
    let output = [];
    for (let i = 0; i < t; i++) {
        const [a, b] = input[lineIndex++].split(' ').map(Number);
        output.push(a + b);
    }
    process.stdout.write(output.join('\n'));
});

 

readline 사용한 게 기본적으로 fs보다 느렸다.

아래)console.log

 

앞으로 문제들은 단순히 해결하는 것뿐만 아니라 더 나은 방법에 대해서도 알 필요가 있는 내용들이 나올듯하다.

728x90
반응형

4번 영수증

문제

준원이는 저번 주에 살면서 처음으로 코스트코를 가 봤다. 정말 멋졌다. 그런데, 몇 개 담지도 않았는데 수상하게 높은 금액이 나오는 것이다! 준원이는 영수증을 보면서 정확하게 계산된 것이 맞는지 확인해보려 한다. 

영수증에 적힌, 

 

- 구매한 각 물건의 가격과 개수

- 구매한 물건들의 총금액

 

을 보고, 구매한 물건의 가격과 개수로 계산한 총금액이 영수증에 적힌 총금액과 일치하는지 검사해 보자.

 

입력

첫째 줄에는 영수증에 적힌 총금액 X가 주어진다. 

둘째 줄에는 영수증에 적힌 구매한 물건의 종류의 수 N이 주어진다. 

이후 N개의 줄에는 각 물건의 가격 a와 개수 b가 공백을 사이에 두고 주어진다.

 

출력

구매한 물건의 가격과 개수로 계산한 총금액이 영수증에 적힌 총금액과 일치하면 Yes를 출력한다. 일치하지 않는다면 No를 출력한다.

 

제한

- 1 ≤ X ≤ 1,000,000,000

- 1 ≤ N ≤ 100

- 1 ≤ a ≤ 1,000,000

- 1 ≤ b ≤ 10

 

첫째 입력 영수증에 적힌 총금액 X, 

두 번째 입력 물건의 종류의 수 N,

이후 각 물건의 가격 a, 개수 b 입력된다.

 

N번 반복문을 돌려서 각 물건의 개수와 가격을 합산하여 X와 비교하여 Yes 또는 No를 출력하면 된다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int total_price;
    int total_count;
    int result = 0;
    cin >> total_price >> total_count;
    for (int i = 0; i < total_count; i++){
        int a, b;
        cin >> a >> b;
        result += a * b;
    }
    if (total_price == result){
        cout << "Yes";
    }
    else cout << "No";
    return 0;
}

 

result 변수 += 연산자 사용 전 값 초기화 필요

 

C#

using System;
class Program{
    static void Main(string[] args){
        int total_price = int.Parse(Console.ReadLine());
        int total_count = int.Parse(Console.ReadLine());
        int result = 0;
        for (int i = 0; i < total_count; i++){
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            int a = int.Parse(arr[0]);
            int b = int.Parse(arr[1]);
            result += a * b;
        }
        if (result == total_price){
            Console.WriteLine("Yes");
        }
        else{
            Console.WriteLine("No");
        }
    }
}

 

Python

total_price = int(input())
total_count = int(input())
result = 0;
for i in range(total_count):
    str = input()
    arr = str.split(' ')
    a = int(arr[0])
    b = int(arr[1])
    result += a * b
if result == total_price:
    print("Yes")
else:
    print("No")

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
let input = [];
let result = 0;
rl.on('line', (line) => {
    input.push(line);
}).on('close', () => {
    const total_price = parseInt(input[0]);
    const total_count = parseInt(input[1]);
    for(let i = 2; i < total_count + 2; i++){
        const[a,b] = input[i].split(' ').map(Number);
        result += a * b;
    }
    if (result === total_price){
        console.log("Yes");
    }else{
        console.log("No");
    }
});

 

모든 입력을 저장하고 인덱스로 끊어서 처리한다.

 

여기서 루프는 처음과 두 번째 값으로 2부터 시작하기 때문에 total_count +  2를 해주어야 전체 값을 처리할 수 있다.

 

5번 코딩은 체육과목입니다.

문제

오늘은 혜나의 면접 날이다. 면접 준비를 열심히 해서 앞선 질문들을 잘 대답한 혜아는 이제 마지막으로 칠판에 직접 코딩하는 문제를 받았다. 

 

혜아가 받은 문제는 두 수를 더하는 문제였다. C++ 책을 열심히 읽었던 혜아는 간단히 두 수를 더하는 코드를 칠판에 적었다. 코드를 본 면접관은 다음 질문을 했다. 

 

“만약, 입출력이 $N$바이트 크기의 정수라면 프로그램을 어떻게 구현해야 할까요?” 

 

혜아는 책에 있는 정수 자료형과 관련된 내용을 기억해 냈다. 책에는 long int는 4바이트 정수까지 저장할 수 있는 정수 자료형이고 long long int는 8바이트 정수까지 저장할 수 있는 정수 자료형이라고 적혀 있었다.

 

혜아는 이런 생각이 들었다. “int 앞에 long을 하나씩 더 붙일 때마다 4바이트씩 저장할 수 있는 공간이 늘어나는 걸까? 분명 long long long int는 12바이트, long long long long int는 16바이트까지 저장할 수 있는 정수 자료형일 거야!” 그렇게 혜아는 당황하는 면접관의 얼굴을 뒤로한 채 칠판에 정수 자료형을 써 내려가기 시작했다. 혜아가 N바이트 정수까지 저장할 수 있다고 생각해서 칠판에 쓴 정수 자료형의 이름은 무엇일까?

 

입력

첫 번째 줄에는 문제의 정수 N이 주어진다. (4 N   1, 000; N은 4의 배수)

 

출력

혜아가 N바이트 정수까지 저장할 수 있다고 생각하는 정수 자료형의 이름을 출력하여라.

 

일리가 있는 생각이다. 혜아는 long이 붙을 때마다 4바이트씩 늘어난다고 생각하여 N바이트를 저장하려면 N/4 * long을 사용하면 N 바이트를 저장할 수 있을 것이라도 추론했다.

 

여기서 N%4가 0이 아니면 N/4 + 1을 해주어야 할 것이지만 N은 4의 배수라고 하니 따로 처리할 필요는 없을 것 같다.

 

물론 실제로는 long long int 까지만 존재하며 그 이상의 크기의 정수를 사용하기 위해서는 __int128_t 또는 gmp 같은 라이브러리를 사용해야 한다. __int128_t는 128비트 정수 자료형으로 16바이트 즉, long long long long int 만큼의 정수를 사용할 수 있다. gmp는 임의 정밀도 연산을 지원하는 라이브러리로 이론적으로 메모리가 허용하는 한 무한히 큰 숫자를 저장할 수 있다.

__int128_t는 <stdint> gmp는 <gmp.h>

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    cin >> n;
    int count = n/4;
    string result;
    for (int i = 0; i < count; i++){
        result += "long ";
    }
    result += "int";
    cout << result;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        string result = "";
        int count = n / 4;
        for (int i = 0; i < count; i++){
            result += "long ";
        }
        result += "int";
        Console.WriteLine(result);
    }
}

 

C++의 경우 string 선언 시 빈 문자열로 초기화가 되지만 C#은 null로 초기화되기 때문에 바로 += 연산을 사용하기 위해서는 빈문자열로 초기화해 주는 게 필요하다.

 

Python

n = int(input())
result = "";
for i in range(n//4):
    result += "long "
result += "int"
print(result)

 

몫을 정확히 구하기 위해서 // 을 사용해야 한다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
rl.question('', (answer)=>{
    const n = parseInt(answer);
    let result = "";
    for (let i = 0; i < n / 4; i++){
        result += "long ";
    }
    result += "int";
    console.log(result);
    rl.close();
});

 

자바스크립트에서 습관적으로 for 문의 변수를 int로 선언하게 되는데 let으로 써야 하는 걸 유의한다.

 

 

728x90
반응형

1번 구구단

문제

N을 입력받은 뒤, 구구단 N단을 출력하는 프로그램을 작성하시오. 출력 형식에 맞춰서 출력하면 된다.

 

입력

첫째 줄에 N이 주어진다. N은 1보다 크거나 같고, 9보다 작거나 같다.

 

출력

출력형식과 같게 N*1부터 N*9까지 출력한다.

 

반복문을 사용하는 문제가 시작되었다. 입력받은 N 값을 1부터 9까지 차례로 곱하고 결과를 출력한다.

 

출력 형식은 

n * 1 = n

n * 2 = 2n 

...

n* 9 = 9n

C++

#include <iostream>
using namespace std;
int main(){
    int n;
    cin >> n;
    for(int i = 1; i < 10; i++){
        cout << n << " * " << i << " = "<< n * i << endl;
    }
    return 0;
}

 

 띄어쓰기와 줄 바꿈 등 출력 형식에 주의한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        int n = int.Parse(input);
        for (int i = 1; i < 10; i++){
            int result = n * i;
            Console.WriteLine($"{n} * {i} = {result}");
        }
    }
}

 

Python

inputStr = input()
n = int(inputStr);
for i in range(1, 10):
    print(f"{n} * {i} = {n*i}");

 

파이썬의 반복문 for i in range()를 사용한다. 

range는 i의 범위로 range(1, 10) 은 i는 1부터 i < 10까지 증가하면서 반복된다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
rl.question('', (answer)=>{
   let n = parseInt(answer);
    for(let i = 1; i < 10; i++){
        console.log(`${n} * ${i} = ${n*i}`);
    }
    rl.close();
});

 

템플릿 리터럴 사용 숙지하기 `` 백틱 내부에서 변수는 ${var}로 문자열과 혼합 표기하면 된다.

반복문에서 i 선언 시 let을 사용해야 한다.

 

2번 A+B-3

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 A+B를 출력한다.

 

처음 입력은 반복 횟수, 다음 줄부터는 A, B의 입력이 한 줄씩 묶어서 여러 묶음이 들어온다.

 

배열과 반복문을 잘 사용해야 할 것 같다. 그런데 제목에는 -3이 있는데 문제와 상관이 없어 보인다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int count;
    cin >> count;
    for (int i = 0; i < count; i++){
        int a, b;
        cin >> a >> b;
        cout << a + b << endl;
    }
    return 0;
}

 

입력받은 값만큼 반복을 한다.

 

반복할 때마다 두 번의 입력을 처리해서 출력하고 다음 루프를 진행한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        int count = int.Parse(Console.ReadLine());
        for (int i = 0; i < count; i++){
            string input = Console.ReadLine();
            string[] inputArr = input.Split(' ');
            int a = int.Parse(inputArr[0]);
            int b = int.Parse(inputArr[1]);
            Console.WriteLine(a+b);
        }
    }
}

 

문제에서 입력이 한 줄씩 들어온다는 점과 Console.ReadLine이 한 줄씩 처리한다는 걸 이해하면 간단하다.

 

이 방법은 반복 횟수가 확정되어 있기 때문에 가능하며 각 줄을 입력받고 연산해서 출력하고 다음 줄로 넘어가는 방식이다.

 

Python

count = int(input())
for i in range(count):
    inputStr = input()
    arr = inputStr.split(' ')
    a = int(arr[0])
    b = int(arr[1])
    print(f"{a + b}")

 

range에 인수를 하나만 넣으면 i = 0부터 시작해서 < count까지 반복한다.

 

input은 문자열이기 때문에 int로 변환해 주는 걸 유의한다.

 

오답

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
rl.question('', (answerCount)=>{
   const count = parseInt(answerCount);
    for (let i = 0; i < count; i++){
        rl.question('', (case)=>{
           const [a, b] = case.split(' ').map(Number);
            console.log(a + b);
        });
    };
    rl.close();
});

 

rl.question 은 비동기 함수라서 반복문 안에서 이를 실행시키면 각 케이스가 독립적으로 처리되지 않기 때문에 위 코드는 제대로 동작하지 않는다.

 

그리고 case는 이미 사용 중인 키워드이기 때문에 이름을 다른 걸 써야 한다.

 

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
rl.question('', (answerCount)=>{
    const count = parseInt(answerCount);
    const results = [];
    let index = 0;
    const ask = ()=>{
        if (index < count){
            rl.question('', (caseInput) =>{
                const [a, b] = caseInput.split(' ').map(Number);
                results.push(a+b);
                index++;
                ask();
            });
        } else{
            results.forEach(result=> console.log(result));
            rl.close();
        }
    };
    ask();
});

 

오답 코드를 개선하여 한 번에 하나씩 케이스를 처리하고, 모든 질문이 완료되면 question을 종료하고 결과를 출력한다.

 

ask 메서드를 변수로 선언하여 각 케이스마다 처리한 결과를 results에 저장해 두고 이 함수를 재귀적으로 호출한다.

 

count까지의 횟수를 체크하기 위해서 index를 사용하여 현재 진행된 반복 횟수를 체크하고 모든 반복이 끝났을 때 저장해 둔 results의 요소들을 모두 출력한다.

 

그리고 이 동작을 실행시키기 위해서 한 번 ask를 실행시켜주어야 한다.

 

더 간단한 방법을 찾아보니 process.stdin을 활용하면 전체 입력을 한 번에 읽고 처리할 수 있는 방법이 있었다.

 

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});

let input = [];
rl.on('line', (line)=>{
    input.push(line);
}).on('close', () => {
    const count = parseInt(input[0]);
    for (let i = 1; i <= count; i++){
        const [a, b] = input[i].split(' ').map(Number);
        console.log(a + b);
    }
    process.exit(0);
});

 

input 배열을 선언하고

 

rl.on('line; ~  각 줄을 입력받을 때마다 input에 저장한다.

 

rl.on('close' ~ 입력이 종료되면 반복문으로 input에 저장된 값들을 처리한다.

 

처음 입력 값인 count 만큼 반복을 실행하며 이를 제외한 i = 1부터 인덱스를 순회한다.

 

1부터 시작되는 input 에는 케이스들이 저장되어 있기 때문에 이 요소를 공백으로 구분하고 맵으로 만들어서 출력해 주면 된다.

 

앞서 풀었던 문제들도 이렇게 풀면 더 간단했던 문제도 있던 거 같았는데 이번에 이 기능들을 제대로 파악하고 가야겠다.

 

3번 합

문제

n이 주어졌을 때, 1부터 n까지 합을 구하는 프로그램을 작성하시오.

 

입력 

첫째 줄에 n (1 ≤ n ≤ 10,000)이 주어진다.

 

출력

1부터 n까지 합을 출력한다.

 

n까지의 합계를 구하는 문제이다.

 

수학 공식을 활용하면 간단하게 n * (n + 1) / 2의 결과와 동일하다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int n;
    cin >> n;
    int result = 0;
    for (int i = 1; i <= n; i++){
        result += i;
    }
    cout << result;
    return 0;
}

 

먼저 문제의 주제에 맞게 반복문을 사용하여 처리해 본다.

 

수학 공식으로 처리해도 동일한 결과라는 것을 확인한다.

 

#include <iostream>
using namespace std;
int main(){
    int n;
    cin >> n;
    int result = n * (n + 1) / 2;
    cout << result;
    return 0;
}

 

반복문 챕터이기 때문에 공식은 아껴두고 반복문으로만 풀어보도록 한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        int result = 0;
        for (int i = 1; i <= n; i++){
            result += i;
        }
        Console.WriteLine(result);
    }
}

 

Python

n = int(input())
result = 0
for i in range(1, n+1):
    result += i
print(result);

 

Node.js

const fs = require('fs');
const n = parseInt(fs.readFileSync('dev/stdin').toString().trim());
let result = 0;
for (let i = 1; i <= n; i++){
    result += i;
}
console.log(result);

 

728x90
반응형

7번 주사위 세 개

문제

1에서부터 6까지의 눈을 가진 3개의 주사위를 던져서 다음과 같은 규칙에 따라 상금을 받는 게임이 있다. 같은 눈이 3개가 나오면 10,000원+(같은 눈) ×1,000원의 상금을 받게 된다. 같은 눈이 2개만 나오는 경우에는 1,000원+(같은 눈) ×100원의 상금을 받게 된다. 모두 다른 눈이 나오는 경우에는 (그중 가장 큰 눈) ×100원의 상금을 받게 된다. 예를 들어, 3개의 눈 3, 3, 6이 주어지면 상금은 1,000+3 ×100으로 계산되어 1,300원을 받게 된다. 또 3개의 눈이 2, 2, 2로 주어지면 10,000+2 ×1,000으로 계산되어 12,000원을 받게 된다. 3개의 눈이 6, 2, 5로 주어지면 그중 가장 큰 값이 6이므로 6 ×100으로 계산되어 600원을 상금으로 받게 된다. 3개 주사위의 나온 눈이 주어질 때, 상금을 계산하는 프로그램을 작성하시오.

 

입력

첫째 줄에 3개의 눈이 빈칸을 사이에 두고 각각 주어진다.

 

출력

첫째 줄에 게임의 상금을 출력한다.

 

입력받은 주사위 눈을 조건에 맞게 검사해서 상금을 출력하면 된다.

 

C++

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a, b, c;
    cin >> a;
    cin >> b;
    cin >> c;
    int reward;
    if (a == b && b == c){
        reward = 10000 + a * 1000;
    }
    else if (a == b || b == c || a == c){
        int val = a == b ? a : b == c ? b : c;
        reward =  1000 + val * 100;
    }
    else{
        int max_val = max({a, b, c});
        reward = max_val * 100;
    }
    cout << reward;
    return 0;
}

 

세 개의 값 중 가장 큰 값을 구할 때 <algorithm> 헤더의 std::max를 사용하여 간략하게 작성한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        string[] arr_input = input.Split(' ');
        int a = int.Parse(arr_input[0]);
        int b = int.Parse(arr_input[1]);
        int c = int.Parse(arr_input[2]);
        int reward;
        if (a == b && b == c){
            reward = 10000 + a * 1000;
        }
        else if (a == b || b == c || a == c){
            int val = a == b ? a : b == c ? b : c;
            reward = 1000 + val * 100;
        }
        else {
            int val = Math.Max(a, (Math.Max(b, c)));
            reward = 100 * val;
        }
        Console.WriteLine(reward);
    }
}

 

C#은 최댓값을 구하기 위해서 Math.Max를 중첩해서 사용했다.

 

다른 방법으로는 System.Linq의 Enumerable.Max를 사용할 수  있다.

using System.Linq;
~

	int [] nums = {a, b, c};
	int max_val = nums.Max();

~

 

두 방식을 비교해 보니 메모리면에서 전자의 방법이 더 나았다.

 

Python

inputData = input();
arrData = inputData.split(' ');
a = int(arrData[0]);
b = int(arrData[1]);
c = int(arrData[2]);
if a == b and b == c:
    reward = 10000 + a * 1000
elif a == b or b == c or a == c:
    val = a if a == b or a == c else b
    reward = 1000 + val * 100;
else:
    val = max(a, b, c)
    reward = 100 * val
print(reward)

 

파이썬에서 삼항 연산자는 if - else로 표현된다.

max 함수는 가장 큰 수를 반환한다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});

rl.question('', (answer)=>{
    const [a,b,c] = answer.split(' ').map(Number);
    let reward;
    if (a == b && b == c){
        reward = 10000 + a * 1000;
    }
    else if (a == b || b == c || a == c){
        let val = a == b ? a : b == c ? b : c;
        reward = 1000 + val * 100;
    }
    else{
        val = Math.max(a, b, c);
        reward = 100 * val;
    }
    console.log(reward);
    rl.close();
});

 

node.js는 Math.max로 세 값 중 가장 큰 값을 구할 수 있다.

728x90
반응형

6번 오븐 시계

문제

KOI 전자에서는 건강에 좋고 맛있는 훈제오리구이 요리를 간편하게 만드는 인공지능 오븐을 개발하려고 한다. 인공지능 오븐을 사용하는 방법은 적당한 양의 오리 훈제 재료를 인공지능 오븐에 넣으면 된다. 그러면 인공지능 오븐은 오븐구이가 끝나는 시간을 분 단위로 자동적으로 계산한다. 또한, KOI 전자의 인공지능 오븐 앞면에는 사용자에게 훈제오리구이 요리가 끝나는 시각을 알려 주는 디지털시계가 있다. 훈제오리구이를 시작하는 시각과 오븐구이를 하는 데 필요한 시간이 분단위로 주어졌을 때, 오븐구이가 끝나는 시각을 계산하는 프로그램을 작성하시오.

 

입력
첫째 줄에는 현재 시각이 나온다. 현재 시각은 시 A (0 ≤ A ≤ 23)와 분 B (0 ≤ B ≤ 59)가 정수로 빈칸을 사이에 두고 순서대로 주어진다. 두 번째 줄에는 요리하는 데 필요한 시간 C (0 ≤ C ≤ 1,000)가 분 단위로 주어진다.

 

출력

첫째 줄에 종료되는 시각의 시와 분을 공백을 사이에 두고 출력한다. (단, 시는 0부터 23까지의 정수, 분은 0부터 59까지의 정수이다. 디지털시계는 23시 59분에서 1분이 지나면 0시 0분이 된다.)

 

훈제오리구이 맛있겠다.

입력은 두 번 들어오고 처음에 현재 시각, 두 번째 조리에 필요한 시간이다.

종료되는 시간은 현재 시각에서 조리 시간을 더한 결과이다. 주의할 점은 조리에 필요한 값은 분 단위로 들어온다는 것으로 이를 시간과 분으로 구분하는 게 계산하기 편할 것 같다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int currH, currM, needM;
    cin >> currH;
    cin >> currM;
    cin >> needM;
    int endH, endM;
    int needH = needM / 60;
    needM = needM - needH * 60;
    endH = currH + needH;
    endM = currM + needM;
    if (endM >= 60){
        endM = endM - 60;
        endH++;
    }
    if (endH >= 24)
        endH = endH - 24;
    cout << endH << " " << endM;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input_first = Console.ReadLine();
        string input_second = Console.ReadLine();
        string[] arr_input_first = input_first.Split(' ');
        int currH = int.Parse(arr_input_first[0]);
        int currM = int.Parse(arr_input_first[1]);
        int needM = int.Parse(input_second);
        int endH, endM;
        int needH = needM / 60;
        needM = needM % 60;
        endH = currH + needH;
        endM = currM + needM;
        if (endM >= 60){
            endM = endM - 60;
            endH++;
        }
        if (endH >= 24)
            endH = endH - 24;
        Console.WriteLine($"{endH} {endM}");
    }
}

 

조리시간을 시간과 분으로 구분할 때 분은 몫으로 계산하면 간략하게 표현할 수 있다.

 

Python

inputFirst = input();
inputSecond = input();
arrInputFirst = inputFirst.split(' ');
currH = int(arrInputFirst[0]);
currM = int(arrInputFirst[1]);
needM = int(inputSecond);
needH = needM // 60;
needM = needM % 60;
endH = currH + needH;
endM = currM + needM;
if endM >= 60:
    endM -= 60
    endH += 1
if endH >= 24:
    endH -= 24
print(endH, endM)

 

파이썬 사용 시 정수 나눗셈에 유의한다. '//'

그리고 증감 연산자 '++' , '--'는 사용하지 못한다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
rl.question('', (answer_first)=>{
    const [currH, currM] = answer_first.split(' ').map(Number);
    rl.question('', (answer_second)=>{
        let needM = parseInt(answer_second);
        let needH = Math.floor(needM / 60);
        needM = needM % 60;
        let endH = currH + needH;
        let endM = currM + needM;
        if (endM >= 60){
            endM -= 60;
            endH++;
        }
        if (endH >= 24){
            endH -= 24;
        }
        console.log(`${endH} ${endM}`);
        rl.close();
    });
});

 

endH의 초기값을 구할 때 Math.floor를 사용해서 정수값을 구한다.

 

728x90
반응형

5번 알람 시계

문제

상근이는 매일 아침 알람을 듣고 일어난다. 알람을 듣고 바로 일어나면 다행이겠지만, 항상 조금만 더 자려는 마음 때문에 매일 학교를 지각하고 있다. 상근이는 모든 방법을 동원해 보았지만, 조금만 더 자려는 마음은 그 어떤 것도 없앨 수가 없었다. 이런 상근이를 불쌍하게 보던 창영이는 자신이 사용하는 방법을 추천해 주었다. 바로 "45분 일찍 알람 설정하기"이다. 이 방법은 단순하다. 원래 설정되어 있는 알람을 45분 앞서는 시간으로 바꾸는 것이다. 어차피 알람 소리를 들으면, 알람을 끄고 조금 더 잘 것이기 때문이다. 이 방법을 사용하면, 매일 아침 더 잤다는 기분을 느낄 수 있고, 학교도 지각하지 않게 된다. 현재 상근이가 설정한 알람 시각이 주어졌을 때, 창영이의 방법을 사용한다면, 이를 언제로 고쳐야 하는지 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 두 정수 H와 M이 주어진다. (0 ≤ H ≤ 23, 0 ≤ M ≤ 59) 그리고 이것은 현재 상근이가 설정한 알람 시간 H시 M분을 의미한다. 입력 시간은 24시간 표현을 사용한다. 24시간 표현에서 하루의 시작은 0:0(자정)이고, 끝은 23:59(다음날 자정 1분 전)이다. 시간을 나타낼 때, 불필요한 0은 사용하지 않는다.

 

출력

첫째 줄에 상근이가 창영이의 방법을 사용할 때, 설정해야 하는 알람 시간을 출력한다. (입력과 같은 형태로 출력하면 된다.)

 

상근이의 아침은 나의 아침과 비슷해 보인다. 문제는 시간과 분이 입력될 때 45분 전의 시간을 출력하면 된다.

24시간 표현을 사용하고, 하루의 시작은 0:0 끝은 23:59인 점을 유의한다. 그리고 표기 시 불필요한 0은 생략

 

C++

#include <iostream>
using namespace std;
int main(){
    int input_h, input_m;
    cin >> input_h;
    cin >> input_m;
    int m = input_m - 45;
    int h = input_h;
    if (m < 0){
        h = input_h - 1;
        m = 60 + m;
        if (h < 0)
        {
            h = 24 + h;
        }
    }
    cout << h << " " << m;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        string[] arr = input.Split(' ');
        int input_h = int.Parse(arr[0]);
        int input_m = int.Parse(arr[1]);
        int m = input_m - 45;
        int h = input_h;
        if (m < 0){
            h = input_h - 1;
            m = 60 + m;
            if (h < 0) {
                h = 24 + h;
            }
        }
        Console.WriteLine($"{h} {m}");
    }
}

 

Python

inputData = input();
inputArr = inputData.split(' ');
inputH = int(inputArr[0]);
inputM = int(inputArr[1]);
h = inputH;
m = inputM - 45;
if m < 0:
    h = inputH - 1;
    m = 60 + m;
    if h < 0:
        h = 24 + h;
print(f"{h} {m}");

 

파이썬에서 문자열에 변수를 사용하는 법

 

1. 문자열 변환

print(str(h) + " " + str(m))

 

2. f-string 

파이썬 3.6 이상부터

print(f"{h} {m}")

 

3. format

print 함수는 여러 인수를 받을 경우 공백으로 구분해서 문자열을 출력한다.

print(h, m)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ');
const inputH = parseInt(input[0]);
const inputM = parseInt(input[1]);
let h = inputH;
let m = inputM - 45;
if (m < 0){
    m = 60 + m;
    h = h - 1;
    if (h < 0){
        h = 24 + h;
    }
}
console.log(`${h} ${m}`);

 

자바스크립트에서 리터럴 템플릿을 사용할 때는 백틱을 사용해야 하며 각각의 중괄호 앞에 $ 표기를 해야 한다.

728x90
반응형

3번 사분면 고르기

문제

흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다. "Quadrant n"은 "제 n사분면"이라는 뜻이다.

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

 

예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다. 점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다. 점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다.

 

입력

첫 줄에는 정수 x가 주어진다. (−1000 ≤ x ≤ 1000; x ≠ 0) 다음 줄에는 정수 y가 주어진다. (−1000 ≤ y ≤ 1000; y ≠ 0)

 

출력

점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

 

x 가 양수인지 음수인지, y가 양수인지 음수인지 구분해서 조건

 

C++

#include <iostream>
using namespace std;
int main(){
    int x, y;
    cin >> x;
    cin >> y;
    char result;
    if (x > 0)
    {
        if (y > 0)
            result = '1';
        else 
            result = '4';
    }
    else{
        if (y > 0)
            result = '2';
        else
            result = '3';
    }
    cout << result;
    return 0;
}

 

 

C#

using System;
class Program{
    static void Main(string[] args){
        string inputX = Console.ReadLine();
        string inputY = Console.ReadLine();
        int x = int.Parse(inputX);
        int y = int.Parse(inputY);
        char result;
        if (x > 0)
        {
            if (y > 0)
                result = '1';
            else 
                result = '4';
        }
        else{
            if (y > 0)
                result = '2';
            else
                result = '3';
        }
        Console.WriteLine(result);
    }
}

 

앞의 문제들과 다르게 각 줄에 값들이 들어온다. 따라서 입력을 따로 두 번 받아서 값을 저장한다.

 

Python

x = int(input());
y = int(input());
if x > 0:
    if y > 0:
        result = '1';
    else:
        result = '4';
else:
    if y > 0:
        result = '2';
    else:
        result = '3';
print(result);

 

파이썬에서 중첩 조건문을 쓸 때는 들여 쓰기로 구분한다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
let x, y;
let result;
rl.question('', (answerX)=>{
    x = parseInt(answerX, 10);
    rl.question('', (answerY)=>{
    y = parseInt(answerY, 10);
        if (x > 0){
            if (y > 0)
                result = '1';
            else
                result = '4';
        }
        else{
            if (y > 0)
                result = '2';
            else
                result = '3';   
        }
        console.log(result);
        rl.close();
    });
});

 

각 각의 입력을 받고 처리한다.

rl.close()가 호출되면 입력된 값을 사용할 수 없기 때문에 호출 전에 결과를 출력해야 한다.

728x90
반응형

3번 윤년

문제

연도가 주어졌을 때, 윤년이면 1, 아니면 0을 출력하는 프로그램을 작성하시오. 윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때이다. 예를 들어, 2012년은 4의 배수이면서 100의 배수가 아니라서 윤년이다. 1900년은 100의 배수이고 400의 배수는 아니기 때문에 윤년이 아니다. 하지만, 2000년은 400의 배수이기 때문에 윤년이다.

 

입력

첫째 줄에 연도가 주어진다. 연도는 1보다 크거나 같고, 4000보다 작거나 같은 자연수이다.

 

출력

첫째 줄에 윤년이면 1, 아니면 0을 출력한다.

 

연도가 4의 배수 && (100의 배수가 아닐 때  || 400의 배수일 때)

 

C++

#include <iostream>
using namespace std;
int main(){
    int input;
    cin >> input;
    char result;
    if ((input % 4) == 0 && ((input % 100) != 0 || (input % 400) == 0))
        result = '1';
    else
        result = '0';
    cout << result;
    return 0;
}

 

배수인지 확인할 때는 나머지가 0인지를 확인하면 된다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        int input = int.Parse(Console.ReadLine());
        char result;
        if ((input % 4) == 0 && ((input % 100) != 0 || (input % 400) == 0))
            result = '1';
        else
            result = '0';
        Console.WriteLine(result);
    }
}

 

Python

inputData = int(input());
if inputData % 4 == 0 and (inputData % 100 != 0 or inputData % 400 == 0):
    result = '1';
else:
    result = '0';
print(result);

 

파이썬의 논리 연산자는 and, or, not으로 작성한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim();
const year = parseInt(input, 10);
let result;
if ((input % 4) == 0 && ((input % 100) != 0 || (input % 400) == 0))
    result = '1';
else
    result = '0';
console.log(result);

 

728x90
반응형

+ Recent posts