[Java] 백준 문제 풀이 - 11720번, 10809번

이진석·2022년 11월 17일
0

백준 문제 풀이!!

목록 보기
9/13
post-thumbnail

20221117

11720번

문제

N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.

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


풀이

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int cnt = sc.nextInt();
        String num = sc.next();
        
        int sum = 0;
        
        for(int i=0; i<cnt; i++) {
            sum += num.charAt(i) - '0';
        }
        
        System.out.println(sum);
    }
}

10809번

문제

알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.

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


풀이

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int []arr = new int[26]; //알파벳
        
        for(int i=0; i<26; i++) {
            arr[i] = -1;
        } //알파벳이 등장하지 않을 경우 -1로 출력
        
        String S = sc.nextLine(); // 단어 입력
        
        for(int i = 0; i < S.length(); i++) {
			char ch = S.charAt(i);
    
			if(arr[ch - 'a'] == -1) {	
				arr[ch - 'a'] = i;
			} // arr 원소 값이 -1 인 경우에만 초기화
		}
 
		for(int val : arr) {
			System.out.print(val + " ");
		}
	}
}
profile
혼자서 코딩 공부하는 전공생 초보 백엔드 개발자 / https://github.com/leejinseok0614

0개의 댓글