Home > database >  Adding digits to a number N times
Adding digits to a number N times

Time:03-11

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!

CodePudding user response:

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.

CodePudding user response:

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)])

CodePudding user response:

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

  • Related