작성일 :

문제 링크

4176번 - Digits

설명

초기값이 주어지고, 다음 값은 현재 값의 자릿수입니다. 수열이 처음으로 같은 값을 반복하는 시점을 찾는 문제입니다.


접근법

첫 번째 값은 초기값의 자릿수 개수입니다. 이후로는 현재 값의 자릿수를 구해 다음 값으로 삼습니다.

현재 값과 다음 값이 같아지면 멈추고 해당 단계를 출력합니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

class Program {
  static void Main() {
    string? s;
    while ((s = Console.ReadLine()) != null) {
      if (s == "END") break;

      if (s == "1") {
        Console.WriteLine(1);
        continue;
      }

      var i = 1;
      var cur = s.Length;
      while (true) {
        var next = cur.ToString().Length;
        i++;
        if (next == cur) {
          Console.WriteLine(i);
          break;
        }
        cur = next;
      }
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;

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

  string s;
  while (cin >> s) {
    if (s == "END") break;

    if (s == "1") {
      cout << 1 << "\n";
      continue;
    }

    int step = 1;
    int cur = s.size();
    while (true) {
      int next = to_string(cur).size();
      step++;
      if (next == cur) {
        cout << step << "\n";
        break;
      }
      cur = next;
    }
  }

  return 0;
}