def f_aux(n, k):
base = (n / (k * 10)) * k
d = n % (k * 10)
if d >= 2*k:
return base + k
elif d >= k:
return base + d%k + 1
return base
def f(n):
k = 1
x = 0
while k <= n:
x += f_aux(n, k)
k *= 10
return x
print f(12345678901234567890)
ZGVmIGZfYXV4KG4sIGspOgogICAgYmFzZSA9IChuIC8gKGsgKiAxMCkpICogawogICAgZCA9IG4gJSAoayAqIDEwKQogICAgaWYgZCA+PSAyKms6CiAgICAgICAgcmV0dXJuIGJhc2UgKyBrCiAgICBlbGlmIGQgPj0gazoKICAgICAgICByZXR1cm4gYmFzZSArIGQlayArIDEKICAgIHJldHVybiBiYXNlCgpkZWYgZihuKToKICAgIGsgPSAxCiAgICB4ID0gMAogICAgd2hpbGUgayA8PSBuOgogICAgICAgIHggKz0gZl9hdXgobiwgaykKICAgICAgICBrICo9IDEwCiAgICByZXR1cm4geAoKcHJpbnQgZigxMjM0NTY3ODkwMTIzNDU2Nzg5MCk=