(구) solved ac class 문제들/class 1

[class 1]백준 숫자의 개수(2577번) 풀이 (C++/Python)

isekaipudding 2026. 4. 22. 12:59

문제 : 숫자의 개수(2577번)(Bronze II)

문제 링크 : https://www.acmicpc.net/problem/2577
출처 : Baekjoon Online Judge

 

문자열->정수 변환 함수를 직접 구현해서 문제를 해결한 적이 있습니다.

이번에는 반대로 정수 -> 문자열로 변환하는 함수를 직접 구현해서 이 문제를 해결해보겠습니다.

string int_to_str(int n) {
    string result = "";

    while(n) {
        char ch = 48 + (n % 10);
        result = ch + result;

        n /= 10;
    }

    return result;
}

우선 132이라는 정수가 들어온다고 가정합니다.

그러면 우선 48 + (132 % 10) 연산을 하여 48 + 2 = 50이 나옵니다.

48은 아스키코드(문자)로 '0'에 해당하므로 50은 '2'가 됩니다.

그 다음 result = "2" + "" = "2"가 됩니다.

그 뒤 n /= 10으로 n은 13이 됩니다.

그 다음 같은 방식으로 48 + (n % 10)에서 51이 되고 51은 '3'에 해당하므로 result = "3" + "2" = "32"가 됩니다.

마지막으로 "1"까지 추가하면 "132"가 되고 n /= 10에 의해 n은 0(falsy 값)이 되므로 while문에서 탈출합니다.

이렇게 정수 132가 문자열 "132"로 반환됩니다.

 

정수 a, b, c가 모두 1000 이하의 자연수이므로 a * b * c는 int 범위 안에 들어갑니다.

이제 C++로 전체 소스 코드를 구현하겠습니다.

#include <bits/stdc++.h>
 
using namespace std;

string int_to_str(int n) {
    string result = "";

    while(n) {
        char ch = 48 + (n % 10);
        result = ch + result;

        n /= 10;
    }

    return result;
}
 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b, c;
    cin >> a >> b >> c;

    string s = int_to_str(a * b * c);
    int size = s.size();

    for(int i = 0; i < 10; i++) {
        int result = 0;
        char ch = 48 + i;

        for(int j = 0; j < size; j++) {
            if(s[j] == ch) result++;
        }

        cout << result << '\n';
    }

    return 0;
}

어차피 a * b * c의 최대값이 1000000000이므로 문자열의 최대 길이는 10이며 이것은 브루트 포스 알고리즘으로 간단하게 해결할 수 있습니다.

 

이제 Python으로 이 문제를 해결해볼까요?

Python은 str()라는 아주 좋은 함수를 가지고 있어서 간단하게 구현할 수 있습니다.

import sys

input = sys.stdin.readline

A:int = int(input().rstrip())
B:int = int(input().rstrip())
C:int = int(input().rstrip())

S:str = str(A * B * C)

for i in range(10) :
    result:int = 0
    ch:str = str(i)
    for s in S :
        if s == ch :
            result += 1
    print(result)