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.4 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6a1d9f98e819ed70a0e994da Challenge 328: Kaprekar's Routine 28 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.

assert.equal(kaprekar(1234), 3);

kaprekar(2025) should return 6.

assert.equal(kaprekar(2025), 6);

kaprekar(7173) should return 4.

assert.equal(kaprekar(7173), 4);

kaprekar(3164) should return 7.

assert.equal(kaprekar(3164), 7);

kaprekar(8082) should return 2.

assert.equal(kaprekar(8082), 2);

--seed--

--seed-contents--

function kaprekar(n) {

  return n;
}

--solutions--

function kaprekar(n) {
  let steps = 0;
  let current = n;

  while (current !== 6174) {
    const digits = String(current).padStart(4, "0").split("").map(Number);
    const desc = parseInt(digits.slice().sort((a, b) => b - a).join(""));
    const asc = parseInt(digits.slice().sort((a, b) => a - b).join(""));
    current = desc - asc;
    steps++;
  }

  return steps;
}