작성일 :

문제 링크

11648번 - 지속

설명

자릿수 곱셈을 반복해 한 자리수가 될 때까지의 단계 수를 구하는 문제입니다.


접근법

문자열로 숫자를 다루며 길이가 1이 될 때까지 반복합니다.

각 자리 문자를 숫자로 바꿔 곱하고, 결과를 다시 문자열로 변환합니다.

이후, 반복 횟수를 누적해 한 자리수가 되면 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;

class Program {
  static void Main() {
    var s = Console.ReadLine()!;
    var steps = 0;
    while (s.Length > 1) {
      steps++;
      var prod = 1;
      foreach (var ch in s)
        prod *= ch - '0';
      s = prod.ToString();
    }
    Console.WriteLine(steps);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;

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

  string s;
  if (!(cin >> s)) return 0;
  int steps = 0;
  while (s.size() > 1) {
    ++steps;
    int prod = 1;
    for (char ch : s)
      prod *= (ch - '0');
    s = to_string(prod);
  }
  cout << steps << "\n";

  return 0;
}