user16627278
user16627278

Reputation:

Adding digits to a number N times

I am a beginner coder and I'm trying to write a code that will add a digit to a number N times. After that it will add the numbers that were added by the digits. For example, when the number is 12 and N is 1 is: 12 + 120 = 132. As another example, when the number is 12 and N is 3, is 12 + 120 + 1200 + 12000 = 13332. I have tried using a loop and adding a string(the digit) to the number but didn't work out as I expected. Is there a way that is simple and neat? Thank you!

Upvotes: 0

Views: 503

Answers (3)

abdeali004
abdeali004

Reputation: 483

I think you looking this type of code.

number = 12
n = 3

num = number

while n:
    number *= 10
    num += number
    n -= 1
print(num)

Output

13332

Upvotes: 0

LukasNeugebauer
LukasNeugebauer

Reputation: 1337

You're always adding a zero, which is the same as multiplying by 10. In base python you can do this:

x = 12
n = 2
outcome = sum([x * (10**i) for i in range(n + 1)])

Upvotes: 2

Szabolcs
Szabolcs

Reputation: 4106

You don't necessarily need strings for this, just a for loop and a summing variable:

number = 12
n = 3
summa = 0
for x in range(n + 1):
    summa += number * (10 ** x)
print(summa)

You can also do it as a fancy one-liner, but since you are at the beginning of your programming career I don't suggest you to start with the cool-kid-on-the-block style.

Upvotes: 3

Related Questions