알고리즘/Algorithm

[기초] 1 - 1. 알고리즘을 시작하기 전에

** C / C++17, Java, Python 언어를 기반으로 진행했으며

모든 문제는 BOJ에서 풀어보실 수 있습니다.**

 

모든 코드는 불펌을 금지하며 학습을 목적으로 글을 작성하였습니다.

코드 작성자 : 본인 (백준 ID: happiness96)


알고리즘을 시작하기 전에


알고리즘을 시작하기 위해서는 먼저 프로그래밍 언어에 대한 기초 지식이 필요하다고 하였다.

자신이 프로그래밍 언어에 대한 기초 바탕이 돼있는지 확인하기 위해 간단히 몇 문제를 풀어볼 것이다.

 

손 풀기 정도로 생각하고 아직 이 정도도 어렵거나 벅차다면 프로그래밍 언어를 더 공부해야 할 때이다.

 


문제 목록


  1. [2557번] Hello World
  2. [1000번] A + B
  3. [9498번] 시험 성적
  4. [2884번] 알람 시계
  5. [10817번] 세 수
  6. [2739번] 구구단
  7. [1110번] 더하기 사이클


1. [2557번] Hello World


☞ 힌트

더보기

간단한 출력 문제이다.

C 언어는 printf, C++은 cout, Java는 System.out.println, Python은 print 함수를 써보자

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    
    printf("Hello World!");

    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    
    cout << "Hello World!";

    return 0;
}
  • Java
더보기
public class Main {
    public static void main(String[] args) {
    
        System.out.println("Hello World!");
        
    }
}
  • Python3
더보기
print('Hello World!')

 


2. [1000번] A + B


☞ 힌트

더보기

간단한 입출력 문제이다.

C언어는 scanf, C++은 cin, python는 input 함수를, Java는 Scanner 모듈을 사용해보자.

☞ Python 2차 힌트

더보기

아직 map 함수를 모른다면 이 문제의 입력을 받는 게 어려울 수 있다.

다른 언어와는 달리 python 언어는 Interpreter 언어이기 때문에 Line 별로 읽어 들여온다.

즉, input 함수를 사용하면 "1 2"가 입력으로 들어오는 것이다.

이를 int 함수로 씌운다고 하면 중간의 공백 때문에 에러를 발생시킬 것이다.

 

이를 해결하기 위해 map 함수가 필요하다.

map 함수에는 두 가지의 파라미터를 넣어줘야 하는데, 첫 번째에는 함수명, 두 번째에는 iterable 한 객체를 넣어주는데 iterable 하다는 말이 뭔지 모르겠다면 Class와 Iterator에 대해 먼저 공부해보자.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int a, b;

    scanf("%d %d", &a, &b);
    printf("%d", a + b);
    
    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int a, b;

    cin >> a >> b;
    cout << a + b;

    return 0;
}
  • Java
더보기
import java.util.Scanner;

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

        a = sc.nextInt();
        b = sc.nextInt();

        System.out.println(a + b);

        sc.close();
    }
    
}
  • Python3
더보기
A, B = map(int, input().split())
print(A + B)

 


3. [9498번] 시험 성적


☞ 힌트

더보기

조건문을 잘 이해하고 있는지 확인하는 문제이다.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int score;

    scanf("%d", &score);

    if (90 <= score && score <= 100) printf("A");
    else if (80 <= score && score <= 89) printf("B");
    else if (70 <= score && score <= 79) printf("C");
    else if (60 <= score && score <= 69) printf("D");
    else printf("F");

    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int score;

    cin >> score;

    if (90 <= score and score <= 100) cout << 'A';
    else if (80 <= score and score <= 89) cout << 'B';
    else if (70 <= score and score <= 79) cout << 'C';
    else if (60 <= score and score <= 69) cout << 'D';
    else cout << 'F';

    return 0;
}
  • Java
더보기
import java.util.Scanner;

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

        if (90 <= score && score <= 100) System.out.println("A");
        else if (80 <= score && score <= 89) System.out.println("B");
        else if (70 <= score && score <= 79) System.out.println("C");
        else if (60 <= score && score <= 69) System.out.println("D");
        else System.out.println("F");

        sc.close();
    }
}
  • Python3
더보기
score = int(input())

if 90 <= score <= 100: print('A')
elif 80 <= score <= 89: print('B')
elif 70 <= score <= 79: print('C')
elif 60 <= score <= 69: print('D')
else: print('F')

 


4. [2884번] 알람 시계


☞ 힌트

더보기

문제 해결 능력을 요구하는 매우 간단한 사칙연산 문제이다.

이 문제에서 "틀렸습니다"를 받는다면 어디선가 조건문 처리를 잘못해준 것이다.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int H, M;

    scanf("%d %d", &H, &M);

    M -= 45;

    if (M < 0){
        M += 60;
        H --;
    }

    if (H < 0) H += 24;

    printf("%d %d", H, M);
    
    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int H, M;

    cin >> H >> M;

    M -= 45;

    if (M < 0){
        M += 60;
        H --;
    }

    if (H < 0) H += 24;

    cout << H << ' ' << M;
    
    return 0;
}
  • Java
더보기
import java.util.Scanner;

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

        M -= 45;

        if (M < 0){
            M += 60;
            H --;
        }

        if (H < 0) H += 24;

        System.out.printf("%d %d", H, M);
        sc.close();
    }
}
  • Python3
더보기
H, M = map(int, input().split())

M -= 45

if M < 0:
    M += 60
    H -= 1

if H < 0:
    H += 24

print(H, M)

 


5. [10817번] 세 수


☞ 힌트

더보기

"A + B" 문제를 풀었다면 입력 받는 것은 그리 문제가 되지 않을 것이다.

정렬을 사용해도 되지만 조건문을 사용해서 간단하게 풀 수 있는 문제다. 

혹시나 "틀렸습니다"를 받았다면 여러가지 세 수를 넣어 정답이 제대로 나오는지 확인해보자.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int A, B, C;

    scanf("%d %d %d", &A, &B, &C);

    if (A > B){
        int tmp = A;
        A = B;
        B = tmp;
    }

    if (B > C){
        int tmp = B;
        B = C;
        C = tmp;
    }

    if (A > B){
        int tmp = A;
        A = B;
        B = tmp;
    }

    printf("%d", B);
    
    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int A, B, C;

    cin >> A >> B >> C;

    if (A > B){
        int tmp = A;
        A = B;
        B = tmp;
    }

    if (B > C){
        int tmp = B;
        B = C;
        C = tmp;
    }

    if (A > B){
        int tmp = A;
        A = B;
        B = tmp;
    }

    cout << B;

    return 0;
}
  • Java
더보기
import java.util.Arrays;
import java.util.Scanner;

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

        int numbers[] = new int[3];

        for (int i = 0; i < 3; i ++){
            numbers[i] = sc.nextInt();
        }

        Arrays.sort(numbers);
        
        System.out.println(numbers[1]);

        sc.close();
    }
}
  • Python3
더보기
numbers = list(map(int, input().split()))

print(sorted(numbers)[1])

 


6. [2739번] 구구단


☞ 힌트

더보기

IT 계열 학과를 다녔다면 한 번쯤은 다들 해봤을 것이다.

반복문을 잘 이해하고 있는지 확인하는 문제이며 "틀렸습니다"를 받았다면 출력 형식을 예제와 같이 제대로 출력했는지 다시 한번 확인해보자.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int N;

    scanf("%d", &N);

    for (int i = 1; i <= 9; i ++) printf("%d * %d = %d\n", N, i, N * i);
    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int N;

    cin >> N;

    for (int i = 1; i <= 9; i ++) cout << N << " * " << i << " = " << N * i << '\n';

    return 0;
}
  • Java
더보기
import java.util.Scanner;

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

        int N = sc.nextInt();

        for (int i = 1; i <= 9; i ++) System.out.printf("%d * %d = %d\n", N, i, N * i);
        sc.close();
    }
}
  • Python3
더보기
N = int(input())

for i in range(1, 10):
    print(N, '*', i, '=', N * i)

 


7. [1110번] 더하기 사이클


☞ 힌트

더보기

반복문 while을 사용할 줄 아는가 테스트해보는 문제이다.

PS를 하면서 문제에서 주어진 입력의 범위를 파악하는 것도 중요한데 이 문제 같은 경우에는 입력이 0보다 크거나 같고, 99보다 작거나 같은 정수이다.

이 범위 내에서 더하기 사이클은 반드시 존재한다.

 


☞ Solution

  • C언어
더보기
#include <stdio.h>

int main(){
    int N, ori, cycle_length = 0;

    scanf("%d", &N);
    ori = N;

    while (1){
        cycle_length ++;
        N = N % 10 * 10 + (N / 10 + N % 10) % 10;

        if (N == ori) break;
    }

    printf("%d", cycle_length);
    
    return 0;
}
  • C++
더보기
#include <iostream>
using namespace std;

int main(){
    int N, ori, cycle_length = 0;

    cin >> N;
    ori = N;

    while (true){
        cycle_length ++;

        N = N % 10 * 10 + (N % 10 + N / 10) % 10;

        if (N == ori) break;
    }

    cout << cycle_length;

    return 0;
}
  • Java
더보기
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(), ori, cycle_length = 0;

        ori = N;
        
        while (true){
            cycle_length ++;
            
            N = N % 10 * 10 + (N / 10 + N % 10) % 10;

            if (N == ori) break;
        }

        System.out.println(cycle_length);

        sc.close();
    }
}
  • Python3
더보기
N = int(input())
ori = N

cycle_length = 0

while True:
    cycle_length += 1

    tmp = (N // 10 + N % 10) % 10

    N = N % 10 * 10 + tmp

    if N == ori:
        break

print(cycle_length)