I came across a programming problem that made me think for a while:
Write a Python program that accepts an integer n and computes the value of
n+nn+nnn+...
This is the programming problem that got me thinking for a while one day, and I saw few correct answers
on internet in the case where n is greater than 9.
Here is about what I have seen the most as a solution:
(we'll limit ourselves here to n+nn+nnn)
python3 example.py
def func(n):
k = n
sum = 0
for i in range(3): #limit n+nn+nnn
sum += k
k = k * 10 + n
return sum
#Output:
#func(1) -> 123
#func(2) -> 246
#func(3) -> 369
#func(4) -> 492
#func(5) -> 615
#func(6) -> 738
#func(7) -> 861
#func(8) -> 984
#func(9) -> 1107
#func(10) -> 1230
For n = 9, we have 1107 (because 9 + 99 + 999 = 108 + 999),
but for n = 10, we get 1230, or 10 + 1010 + 101010 is much higher, since
1230 < 101010.
The problem here is that we multiply k by 10 and then we add
n.
example with n = 9:
9 * 10 = 90
90 + 9 = 99
but for n = 10:
10 * 10 = 100
100 + 10 = 110
However, we're looking for 1010. A solution would be to make a condition like if
n > 9, then there we multiply by 100 instead of 10, but it does
not look clean.
The solution:
python3 solution.py
def func(n):
m = []
k = ''
for i in range(3):
k += str(n)
m.append(int(k))
sum = 0
for j in range(len(m)):
sum = sum + int(m[j])
return sum
#Output:
#func(10) -> 102030
#func(20) -> 204060
#func(100) -> 100200300
#func(1000) -> 100020003000
Thus, for n = 10, we obtain 102030.