본문 바로가기

PS_Baekjoon

[백준 C++] 14912번 : 숫자 빈도수

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

 

14912번: 숫자 빈도수

자연수 n (1 ≤ n ≤ 100,000)과 한 자리 숫자 d(0~9)가 첫째 줄에 주어진다.

www.acmicpc.net

풀이 :

- 1부터 n까지의 숫자에서 각 숫자(digit)의 갯수를 카운트하고, 주어진 수의 digit이 몇 개인지 출력하는 문제

- 숫자보다는 문자열로 탐색하는게 편해서 문자열로 변환해서 각 자리수를 카운트했다

- 1부터 n까지 for문을 돌리고 i를 문자열로 변환한 뒤, 각 자리수를 카운트하는 배열에 카운트해서 넣어줬다

 

코드 :

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

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

    int n, digit, cnt[10] = {0, };
    string s;

    cin >> n >> digit;
    for(int i=1; i<=n; i++){
        s = to_string(i); //i를 문자열로 변환
        for(int j=0; j<s.size(); j++){ //변환된 i를 탐색하며
            cnt[s[j]-'0']++; //각 자리수를 카운트
        }
    }
    cout << cnt[digit] << '\n'; //주어진 digit이 가리키는 인덱스 출력
}