[C++, python] 백준 14912번 풀이 ( 숫자 빈도수 )

정민경·2024년 1월 9일
0

baekjoon

목록 보기
53/57
post-thumbnail

- 문제 ( 14912번 ) : 숫자 빈도수

  • 1 ~ n 까지 차례로 숫자를 써 내려갈 때 특정 숫자의 빈도수를 구하여 출력하는 프로그램 작성.
    • n = 11 이고 특정숫자가 1일때
      => 1 2 3 4 5 6 7 8 9 10 11 -> 1이 총 4번 등장.

- 입력 및 출력

[ 입력 ]

  • 자연수 n 과 한 자리 숫자 d 가 첫째 줄에 공백을 사이에 두고 입력.
    ( 1 ≤ n ≤ 100,000, d 는 0~9 숫자 )

[ 출력 ]

  • 첫째 줄에 빈도 수 출력.

- 문제 풀이

  • 이번 14912 번 숫자 빈도수 문제는 1부터 입력받은 n 까지 반복문을 돌면서 입력받은 특정 숫자 d 가 몇번 나오는지 count 하면 되는 굉장히 간단한 문제이다.

    반복하는 숫자 n 은 100,000 까지 나올 수 있기 때문에 특정 숫자가 나올 수 있는 자리도 최대 6자리이다. 그렇기 때문에 숫자로 비교하는 것이 아닌 문자열로 비교하는 방식으로 문제를 해결했다.

  • step1) 숫자를 문자열로 변환
  • step2) 문자열 == 문자의 배열이므로 문자열의 가장 처음부터 뒤까지 반복하며 입력받은 숫자 d 와 비교
    이 때 d 와 같으면 count 값 1 증가
  • step3) n번째 숫자까지 전부 비교를 했다면 count 값 출력


- 최종 코드

  • c++ code
#include <iostream>
#include <string>

int main() {
  int n = 0;
  char digit = ' ';
  int count = 0; // frequency of digit

  // input n & digit
  std::cin >> n >> digit;

  // change int to string
  for(int i = 1; i <= n; i++) {
    std::string num = std::to_string(i);

    for(int j = 0; j < num.length(); j++) {
      if (num[j] == digit) {
        count ++;
      }
    }
  }

  // print result ( = count )
  std::cout << count << std::endl;

  return 0;
}
  • python code
# input n, digit
n, digit = map(int, input().split())

count = 0 # frequency of digit

# iterator 1 to n
for i in range(1, n+1):

  # convert int to string
  for a in str(i):
    if int(a) == digit:
      count += 1

# print result
print(count)

0개의 댓글