Ask Question
6 February, 19:08

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.

+5
Answers (1)
  1. 6 February, 19:21
    0
    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=" ")

    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
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “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 ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers