Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python how many moves to get to zero

I have tried to do this task in a lot of ways but none of it works.

The user enters a natural number n. In one move, its largest digit is subtracted from the number. In the next move, its highest digit is subtracted from the result, etc. The program needs to determine and print how many moves it takes to get to zero. For example, number 24 requires five moves (24 → 20 → 18 → 10 → 9 → 0).

Here is what I’ve done so far. I know how to find the largest digit but how can I put this into a loop to substract largest digit from result ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

num = int(input("Enter natural number "))

if num <= 0:
    print("That is not a natural number")
else:
    max = 0
    while num > 0:
        digit = num % 10
        if max < digit:
            max = digit
        num = num // 10
    print("Largest Digit is : ", max)

>Solution :

You could try with a string and max:

num = int(input("Enter natural number "))

if num <= 0:
    print("That is not a natural number")
else:
    ntimes = 0
    while num > 0:
        num -= int(max(str(num)))
        ntimes += 1
    print(ntimes)

Output:

5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading