Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Reduce a number by its largest digit

Task:

Given an integer number in decimal number system, reduce it to a single decimal digit as follows:

  1. Convert the number to a list of decimal digits.
  2. Find the largest digit, D
  3. Remove D from the list. If there is more than one occurrence of D, choose the first from the left (at the most significant position), all others should remain intact.
  4. Convert the resulting list to a decimal number and multiply it by D.
  5. If the number is bigger than 9 (has more than 1 decimal digit), repeat the whole procedure, feeding the result into it. Stop when you get a single-digit result.
  6. Display the result.

Example:

26364 -> 
1. 2 6 3 6 4 
2. The largest digit is 6, so D=6
3. There are two occurrences or 6: at positions 1 and 3 (0-based). We remove the left one,
 at position 1 and get the list 2 3 6 4 
4. we convert the list 2 3 6 4 to 2364 and multiply it by D:
 2364 * 6 = 14184
5. 14184 is greater than 9 so we repeat the procedure, feeding 14184 into it.

We continue by repeating the procedure for 14184 and so on and we go through the following intermediate results, finally reaching 8:

11312
3336
1998
1782
1376
952
468
368
288
224
88
64
24
8

So the result for 26364 is 8.

Input: An integer / a string representing an integer

Output: A single digit, the result of the reduction applied to the number.

Test cases:

9 -> 9
27 -> 4
757 -> 5
1234 -> 8
26364 -> 8
432969 -> 0
1234584 -> 8
91273716 -> 6

This is , so the shortest answers in bytes in each language win.

Answer*

Draft saved
Draft discarded
Cancel
7
  • 1
    \$\begingroup\$ ...I was debugging a dumb mistake in this. Darn, I got ninja'd. \$\endgroup\$ Commented Nov 18, 2017 at 20:21
  • \$\begingroup\$ I'm getting an error on input 9 \$\endgroup\$ Commented Nov 19, 2017 at 7:27
  • \$\begingroup\$ This seems to fail for the test case 432969. "ValueError: invalid literal for int() with base 10: ''" \$\endgroup\$ Commented Nov 20, 2017 at 13:25
  • \$\begingroup\$ @JamesWebster should be fixed now. \$\endgroup\$ Commented Nov 20, 2017 at 18:15
  • 1
    \$\begingroup\$ @recursive No, as then if n was 0 then n*(n<=9) would still evaluate to a falsy value, 0, making the recursion continue and causing an error, whereas the string '0' is a truthy value and therefore the recursion is halted. \$\endgroup\$ Commented Nov 21, 2017 at 22:16

AltStyle によって変換されたページ (->オリジナル) /