25
1
Related: Program my microwave oven. Inspired by Generate lazy microwave input.
The lazy value of the non-negative integer N is the smallest of the integers that are closest to N while all their digits are identical.
Return (by any means) the lazy value of a given (by any means) N.
N ≤ the largest integer that your language represents in non-exponent form by default. 1000000 (A lot of interesting solutions are lost because of this too-high requirement.)
Test cases:
0 → 0
8 → 8
9 → 9
10 → 9
16 → 11
17 → 22
27 → 22
28 → 33
100 → 99
105 → 99
106 → 111
610 → 555
611 → 666
7221 → 6666
7222 → 7777
The colleague in question proved that there will be no ties: Except for 9/11, 99/111, etc. for which one is shorter than the other, two consecutive valid answers are always an odd distance apart, so no integer can be exactly equidistant from them.
@user81655 I've added some alternative versions with their numeric limitations. – Neil – 2016-02-23T11:44:53.727
1I couldn't get this algorithm to work with
Number.MAX_SAFE_INTEGER
either because8e16 - 1
is expressed as8e16
. Sadly, it looks like the only way would be hard-coding the maximum result. +1 nonetheless. – user81655 – 2016-02-23T11:54:41.137@user81655 I lowered the upper bound to allow the solution. – Adám – 2016-02-23T19:17:24.547
Got you to 10k @Neil, love the golfs! – NiCk Newman – 2016-06-08T02:39:56.163
1@NiCkNewman Woohoo! Thanks! – Neil – 2016-06-08T07:36:22.280
Could you explain this for those of us unfamiliar with Javascript? – ngenisis – 2017-01-13T01:25:06.160
@ngenisis Because lazy values are of the form k((10^n)-1)/9, multiplying the original number by 9 should give you a number near to k10^n. Adding 4 and calling
toPrecision
achieves the necessary rounding. It then remains to regenerate the lazy value given k*10^n. – Neil – 2017-01-13T09:05:42.827