Files
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

1.7 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6a1d9f98e819ed70a0e994da Challenge 328: Kaprekar's Routine 29 challenge-328

--description--

Given a 4-digit number, return the number of times you need to apply Kaprekar's routine until reaching 6174.

Kaprekar's routine works as follows:

  • Arrange the digits in descending order to form the largest number
  • Arrange the digits in ascending order to form the smallest number (pad with leading zeros if necessary)
  • Subtract the smaller from the larger
  • Repeat with the new number

--hints--

kaprekar(1234) should return 3.

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(kaprekar(1234), 3)`)
}})

kaprekar(2025) should return 6.

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(kaprekar(2025), 6)`)
}})

kaprekar(7173) should return 4.

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(kaprekar(7173), 4)`)
}})

kaprekar(3164) should return 7.

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(kaprekar(3164), 7)`)
}})

kaprekar(8082) should return 2.

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(kaprekar(8082), 2)`)
}})

--seed--

--seed-contents--

def kaprekar(n):

    return n

--solutions--

def kaprekar(n):
    steps = 0
    current = n
    while current != 6174:
        digits = list(str(current).zfill(4))
        desc = int("".join(sorted(digits, reverse=True)))
        asc = int("".join(sorted(digits)))
        current = desc - asc
        steps += 1
    return steps