19.8k views
4 votes
Your task is to break a number into its individual digits, for example, to turn 1729 into 1, 7, 2, and 9. It is easy to get the last digit of a number n as n % 10. But that gets the numbers in reverse order. Solve this problem with a stack. Your program should ask the user for an integer, then print its digits separated by spaces.

User Aniello
by
4.9k points

1 Answer

7 votes

Answer:

stack = []

number = int(input("Enter a number: "))

while number > 0:

stack.append(number % 10)

number = int(number / 10)

while len(stack) > 0:

print(stack.pop(), end=" ")

Step-by-step explanation:

Initialize an empty list to represent the stack

Get a number from the user

Create a while loop that iterates through the given number and append its last digit to stack

When the first loop is done, your stack is filled with the digits of the given number

Create another while loop that iterates through your stack and prints its elements, digits of the number, separated by spaces

User Jxmallett
by
4.3k points