1427. Kaprekar Countdown

Easy1.5 points estimatedMathsSimulationSorting
RPby Rohit Parihar1 submission

A puzzle magazine runs a digit game on four-digit numbers. Start with n, keeping exactly four digits with leading zeros (so 999 is treated as 0999). In one step, arrange the digits in descending order to get the larger number, arrange them in ascending order to get the smaller number, and replace the current number by their difference, again as four digits. Return how many steps are needed until the number becomes 6174, or 0 if n is already 6174. The digits of n are never all equal, and every such start reaches 6174 after a handful of steps, so the running time is O(1) with O(1) extra space.

Example 1

Input:
n = 3524
Output:
3
Explanation:

3524 gives 5432-2345 = 3087, then 8730-0378 = 8352, then 8532-2358 = 6174, which is 3 steps.

Example 2

Input:
n = 6174
Output:
0
Explanation:

The number is already 6174, so no steps are needed.

Constraints

1000 ≤ n ≤ 9999
The digits of n are not all equal.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…