Problems > Kaprekar's Routine

Kaprekar's Routine

Difficulty: 1300 2000 ms 128 MB

math implementation

Treat N as a 4-digit number (pad with leading zeros). Repeatedly sort its digits descending and ascending and subtract; all such numbers (with at least two distinct digits) reach 6174. Print how many steps N needs (0 if N is already 6174).

Input: one integer N with at least two distinct digits when zero-padded to 4 digits.

Output: the number of steps to reach 6174.

Constraints:

  • 1 ≤ N ≤ 9998

Sample Tests

Input 1
3524
Output 1
3
Input 2
6174
Output 2
0

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.