How can I get a repdigit?
Haskell, 39 bytes
until(((==).head>>=all).show)(+1)>>=(-)
Try it online
Brachylog, 9 bytes
:.#++#==,
Try it online!
This is pretty efficent as it makes use of constraints arithmetic.
Explanation
:. The list [Input, Output].
#+ Both elements must be positive or zero.
+ The sum of those two elements…
#= …must result in an integer where all digits are the same.
=, Assign a value that matches those constraints.
Python 2, 41 40 bytes
def f(n):r=10**len(`n`)/9;print-n/r*-r-n
Not the shortest approach, but very efficient. Test it on Ideone.
How it works
For input 10**len(`n`)
rounds n up to the nearest power of 10. Afterwards, we divide the result by 9. This returns the repdigit 1…1 that has as many digits as n. We save the result in r. For example, if n = 87654321, then r = 11111111.
The desired repdigit will be a multiple or r. To decide which, we perform ceiling division of n by r. Since Python 2's division operator /
floors, this can be achieved with -n/r
, which will yield the correct absolute value, with negative sign. For example, if n = 87654321, this will return -8.
Finally, we multiply the computed quotient by -r to repeat the quotient once for each digit in n. For example, if n = 87654321, this returns 88888888, which is the desired repdigit.
Finally, to calculate the required increment, we subtract n from the previous result. For our example n = 87654321, this returns 1234567, as desired.