🧐 백준 1427, 1676, 2577, 2711  _ 단일 숫자에 대한 리스트를 이용한 접근

🤫 해결의 실마리 

🤔 단일숫자나 문자열에 대한 접근이나 리스트로 어떻게 바꿀까?

🙃 단일 숫자의 경우는 다음과 같다.
1. 단일 숫자를 문자열로 바꾼다.
2. 문자열을 리스트에 넣는다.
str_num = str(n)
str_list = list(str_num)​

🙃 문제에 맞는 연산 진행 후 다시 숫자로 출력하고 싶다면?
3. 리스트값들을 출력
print(*sorted(num, reverse = True) , sep = '')
# sep=''를 통해 원소간의 구분자인 공백을 없애줌으로
# 9 9 9 9 9 9 9 9 8 을
# 999999998 로 출력​


🧐 사용법에 대한 정리.

num = int(input())
str_x = list(str(num))          # ['1', '2', '3', '4', '5', '6']
int_x = list(map(int, str_x))   # [1, 2, 3, 4, 5, 6]

print(*int_x)           # 1 2 3 4 5 6
print(*int_x, sep="")   # 123456


 
🤔  원하는 원소를 어떻게 지울까?  pop, del, remove 함수! 
# cf-1  pop
a = [1,2,1,3,4,5,1]
removed = a.pop(1)  # 1번째 index 삭제 단, return 가능

print(a)            # [1, 1, 3, 4, 5, 1]
print(removed)      # 2   <-- pop한 원소를 return 가능
# cf-2  del  -> pop과 다르게 리스트의 범위를 지정해 삭제 가능
a = [1,2,1,3,4,5,1]

del a[:2]
print(a)        # [1, 3, 4, 5, 1]
#cf-3   remove  -> 위와 달리 지우고자 하는 인덱스가 아닌 값을 입력
for _ in numbers :
    numbers.remove(3)




🤫  solution_1427

# 입력: 999998999

num = list(map(int, input()))  # 공백없이 입력받을 때, list에 저장하는 법
print(*sorted(num, reverse = True) , sep = '')
# sep=''를 통해 원소간의 구분자인 공백을 없애줌으로
# 9 9 9 9 9 9 9 9 8 을
# 999999998 로 출력

# cf. end옵션을 사용하면 그 뒤에 나오는 출력값과 구분을 짓는 구분자 역할을 한다.
print(*sorted(num, reverse = True) , end = " hello ")
print(num)
# 9 9 9 9 9 9 9 9 8 hello [9, 9, 9, 9, 9, 8, 9, 9, 9] 가 출력


🤫  solution_1676

def fac(n):
    if n <= 1:
        return 1
    else:
        return n * fac(n - 1)

N = int(input())
n = fac(N)

# 숫자를 리스트에 한자리씩 넣기 (숫자->문자열)
str_num = str(n)
str_list = list(str_num)

cnt = 0
for i in reversed(str_list):
    if i == '0':
        cnt += 1
    else:
        break
print(cnt)

 

🤫  solution_2577

num = []
for i in range(3):
    n = int(input())
    num.append(n)

mul = 1
for i in range(3):
    mul *= num[i]

str_x = list(str(mul))
int_x = list(map(int, str_x))

out_ls = []
for i in range(10):
    out_ls.append(int_x.count(i))

for i in range(10):
    print(out_ls[i])

 

 

🧐 백준 1292 , 4458 풀이 및 사용함수

🤫 해결의 실마리 

🤔 리스트 사용의 핵심! 인덱스 슬라이싱 
인덱스 슬라이싱에 대한 응용방법을 아래 해설을 통해 볼 수 있는데, [:]를 이용한다.



🤫  solution_1292

A, B = map(int, input().split())
num_sequences = []

for i in range(1000):
    for j in range(i):
        num_sequences.append(i
print(sum(num_sequences[A-1:B]))


🤫  solution_4458

for i in [input() for _ in range(int(input()))]:
    print(i[:1].upper() + i[1:])

 

 

 

🧐 백준 1157  풀이 및 사용 함수

🤫 해결의 실마리 

🤔 원소가 겹치지 않아? set 자료구조 
주로 사용하는 리스트로 set을 변환하는 방법은 다음과 같다.
a_set = set(a)
lst = []
for i in a_set:
    lst.append(a.count(i))


🤫  solution_1546

a = list(str(input()).upper())
a_set = set(a)
cnt = []
for i in a_set:
    cnt.append(a.count(i))
if cnt.count(max(cnt)) <= 1:
    print(max(a, key = a.count))
else:
    print("?")

 

🧐 백준 1292 , 4458 풀이 및 사용함수

🤫 해결의 실마리 

🤔 리스트 사용의 핵심! 인덱스 슬라이싱 
인덱스 슬라이싱에 대한 응용방법을 아래 해설을 통해 볼 수 있는데, [:]를 이용한다.



🤫  solution_1292

A, B = map(int, input().split())
num_sequences = []

for i in range(1000):
    for j in range(i):
        num_sequences.append(i
print(sum(num_sequences[A-1:B]))


🤫  solution_4458

for i in [input() for _ in range(int(input()))]:
    print(i[:1].upper() + i[1:])

 

🧐 백준 2309,  2822 풀이 및 사용함수

🤫 해결의 실마리 

🤔 정렬을 스스로 해주는 내장함수, sorted를 이용하자! 

정렬 함수는 다음 2가지를 사용할 수 있다.

a.sort()
sorted(a)

둘의 차이는 바로 반환의 여부이다.
a.sort의 경우, 반환을 해주지 않기에 print문에 넣어주면 오류가 발생하게 된다.
하지만 sorted의 경우, 값의 반환이 이루어질 수 있어서 print문에서도 오류가 발생하지 않는다.


🤔 cf. 출력 조건에 따라 다음과 같이 작성하자!
sorted(idx_list)  => [3, 4, 5, 6, 8]
*sorted(idx_list) =>   3 4 5 6 8


🤫  solution_2309

dwarf = [int(input()) for _ in range(9)]

for i in range(len(dwarf)):
    for j in range(i+1, len(dwarf)):
        if (sum(dwarf) - (dwarf[i] + dwarf[j])) == 100:
            dwarf1, dwarf2 = dwarf[j], dwarf[i]  # out of index range 조심
            dwarf.remove(dwarf1)
            dwarf.remove(dwarf2)
            break
        else:
            continue

print(*sorted(dwarf), sep = "\n")

 

🤫  solution_2822

score = [int(input()) for _ in range(8)]
total = list(sorted(score, reverse=True))
print(sum(total[:5]))

idx_list = []
for i in range(5):
    idx_list.append(score.index(max(score)) + 1)
    score[score.index(max(score))] = -100
print(*sorted(idx_list))
# sorted(idx_list)  => [3, 4, 5, 6, 8]
# *sorted(idx_list) =>   3 4 5 6 8

 

 

🧐 백준 11047 풀이

🤫  solution_11047  (Greedy Algorithm)

N, K = map(int, input().split())

coin = sorted([int(input()) for _ in range(N)], reverse=True)

cnt = 0
while K != 0:
    for i in range(N):
        if coin[i] > K:
            i -= 1
        else:
            frequency = K // coin[i]
            K -= coin[i] * frequency
            cnt += frequency
print(cnt)

 

🫠 백준 1152(https://www.acmicpc.net/problem/1152)

 

1152번: 단어의 개수

첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열

www.acmicpc.net

🧐 Algorithm _ 단어의 개수 세는 법
1. 단어의 개수를 세는 대신 띄어쓰기를 기준으로 하여 공백의 개수를 세었다.
(∵ 단어를 구분짓는 기준이 띄어쓰기이기 때문)

2. getline 함수를 이용해 cin으로 받은 입력값을 str이라는 변수에 저장해 주었다.
이때, 저장되는 값들은 모두 char 형이다.
예를 들어 hello라는 변수를 입력하면, str[1] = 'e'가 되는 것이다.

3. 그 후 공백에 해당하는 문자 ' ' 의 개수를 세워주기만 하면 된다.

4. 다만, 주의할 점은 가장 앞에 공백이 나오는 경우와 가장 뒤에 공백이 들어가는 경우이다.
이와 관련하여 가장 앞에 공백이 나오는 경우를 삼항연산자로 처리해 주었고
가장 뒤에 공백이 들어가는 경우는 for문에서 str.size()-1 을 해줌으로 처리해 주었다.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string str;
    getline(cin, str);  // getline(cin, str, '\n');
    // cin.getline(char str, streamsize n, char dlim); delim을 만나기 전까지의 모든 문자를 읽어 str배열에 저장.

    int cnt_space = 0;

    for (int i = 0; i < str.size() - 1; i++) {
        if (str[i] ==' ')
            cnt_space++;
    }
    int cnt = (str[0] == ' ') ? cnt_space : cnt_space + 1;
    cout << cnt;
}


 

 

 

 

 

 

 

🫠 백준 1157(https://www.acmicpc.net/problem/1157)

 

1157번: 단어 공부

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

www.acmicpc.net

🧐 Algorithm _ 왜 틀리는거지...
1. 소문자와 대문자의 구별을 없애기 위해 소문자를 대문자로 바꿔준다.
2. 알파벳을 총 25개이므로 각각의 알파벳의 개수를 세주기 위한 count배열 생성
3. count한 값이 2개 이상이라면(max와 동일한 count값이 있다면) ? 출력
4. 그게 아니라면 max값에 해당하는 index에 해당하는 알파벳 출력

1번.

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string str;
    getline(cin, str);

    // 1. 소문자와 대문자의 구별을 없애야 함
    for (int i = 0; i < str.length(); i++){
        if (str[i] >= 'a' && str[i] <= 'z')
            str[i] = str[i] - 'a' + 'A';
    }
    // 2. 알파벳은 총 25개(Z-A = 25)이므로 count를 위한 배열을 생성 및 초기화해줘야함
    int count[26];    for (int i = 0; i < 26; i++)    count[i] = 0;

    for (int i = 0; i < str.length(); i++){
        int idx_number = str[i] - 65;
        count[idx_number]++;
    }

    char c;
    int max = -1;

    for (int i = 0; i < 26; i++){
        if (count[i] == 0)
            continue;
        else if (count[i] > max){
            max = count[i];
            c = (char)(i + 65);
        }
        else if (count[i] == max){
            c = '?';
        }
    }
    cout << c;
}

 

 

 2번.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string str;
    getline(cin, str);

    // 1. 소문자와 대문자의 구별을 없애야 함
    for (int i = 0; i < str.length(); i++){
        if (str[i] >= 'a' && str[i] <= 'z')
            str[i] = str[i] - 'a' + 'A';
    }
    // 2. 알파벳은 총 25개(Z-A = 25)이므로 count를 위한 배열을 생성 및 초기화해줘야함
    vector<int> alpha_count(26);    for (int i = 0; i < 26; i++)    alpha_count[i] = 0;

    for (int i = 0; i < 26; i++){
        int idx_number = str[i] - 65;
        alpha_count[idx_number]++;
    }

    int max = *max_element(alpha_count.begin(), alpha_count.end());
    int cnt = count(alpha_count.begin(), alpha_count.end(), max);
    int index = max_element(alpha_count.begin(), alpha_count.end()) - alpha_count.begin();

    if (cnt >= 2)
        cout << "?";
    else if (cnt < 2)
        cout << (char)(index + 65);
}

 

 

 

 

 

 

🫠 백준 11720(https://www.acmicpc.net/problem/11720)

 

11720번: 숫자의 합

첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다.

www.acmicpc.net

🧐 Algorithm _ 한줄에 입력을 모두 공백없이 받기
1. 먼저 공백없이 입력을 받아 저장하는 string 변수 str과
2. string을 char배열에 넣기 위한 작업을 진행한다.
char c[str.length()+1] 이라는 배열을 생성해주고
이 배열에 str에 저장된 문자열을 집어넣어 주기 위해 copy함수를 사용해준다.

3. 그 후 char 형의 5를 int 형의 5로 바꿔줘야 하므로 다음과 같은 방법을 이용해 준다.
9 = '9'-'0'  (= 57 - 48)
위와 같은 방법을 이용하면 c[i] - '0'은 해당 숫자와 동일한 값을 갖게 된다.

4. 이후 최종적으로 sum이라는 변수에 최종적인 값들의 합을 저장해주면 된다.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int num;    cin >> num;
    string str; cin >> str;
    int sum = 0;

    char c[str.length() + 1];
    str.copy(c, str.length() + 1);

    int arr[str.length() + 1];
    for (int i = 0; i < str.length(); i++) {
        arr[i] = c[i] - '0';
    }

    for (int i = 0; i < str.length(); i++) {
        sum += arr[i];
    }
    cout << sum;
}

 

 

 

 

 

 

+ Recent posts