한 발짜국

알고리즘 #6 (백준 11721, 2741, 2742, 2739, 1924번) [Java] 본문

알고리즘&자료구조

알고리즘 #6 (백준 11721, 2741, 2742, 2739, 1924번) [Java]

발짜국 2021. 9. 23. 03:50

백준 알고리즘 6일차

어제 하루 빠졌지만.. 추석이니까!!

 

[2021.9.22]

백준 11721번 (Java)

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

 

11721번: 열 개씩 끊어 출력하기

첫째 줄에 단어가 주어진다. 단어는 알파벳 소문자와 대문자로만 이루어져 있으며, 길이는 100을 넘지 않는다. 길이가 0인 단어는 주어지지 않는다.

www.acmicpc.net

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String word = sc.next();
        
        for(int i=0; i<word.length(); i++) {
            System.out.print(word.charAt(i));
            if((i+1) % 10 == 0) {
                System.out.println();
            }
        }
    }
}

.substring()을 이용해서 10개씩 나눠 출력하려고 했는데, 다른 분들의 풀이에 더 효율적인 방법이 있었다.

 

백준 2741번 (Java)

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

 

2741번: N 찍기

자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.

www.acmicpc.net

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        
        for(int i=1; i<=num; i++) {
            System.out.println(i);
        }
    }
}

 

백준 2742번 (Java)

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

 

2742번: 기찍 N

자연수 N이 주어졌을 때, N부터 1까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.

www.acmicpc.net

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        
        for(int i=num; i>0; i--) {
            System.out.println(i);
        }
    }
}

 

백준 2739번 (Java)

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

 

2739번: 구구단

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

www.acmicpc.net

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        
        for(int i=1; i<=9; i++) {
            System.out.println(num + " * " + i + " = " + num*i);
        }
    }
}

 

백준 1924번 (Java)

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

 

1924번: 2007년

첫째 줄에 빈 칸을 사이에 두고 x(1 ≤ x ≤ 12)와 y(1 ≤ y ≤ 31)이 주어진다. 참고로 2007년에는 1, 3, 5, 7, 8, 10, 12월은 31일까지, 4, 6, 9, 11월은 30일까지, 2월은 28일까지 있다.

www.acmicpc.net

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int month = sc.nextInt();
        int day = sc.nextInt();
        sc.close();
        
        int daysOfMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        String dayOfWeek[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
        int totalDays = day;
        
        for(int i=0; i<month-1; i++) {
            totalDays += daysOfMonth[i];
        }
        
        System.out.println(dayOfWeek[totalDays%7]);
    }
}

1일일때 "MON"이니, 배열이 0은 "SUN"으로 시작하는게 런타임 에러를 피하기 좋다.

반응형
Comments