Home > Python >Python Exercise: Steps To Zero

Steps To Zero

Given a positive integer, write a function to return the number of steps needed to make the result to be zero by following the process:
  • If the number even number, divide the number by 2
  • If the number is an odd number and divisible by 3, then divide the number by 3
  • If the number is an odd number and not divisible by 3, then subtract 1 from the number

You need login to comment

Solution submitted by Dzeng at March 19, 2020, 11:53 p.m.
def step1 (num): return num // 2 def step2 (num): return num // 3 def step3 (num): return num - 1 steps = 0 num = int(input("type a number")) while num != 0: if num % 2 == 0: num = step1(num) print(num) elif num % 3 == 0: num = step2(num) print(num) else: num = step3(num) print(num) steps += 1 print("steps to zero is", steps)
Solution submitted by Andrew at May 25, 2020, 3:58 p.m.
def stepstozero(num): steps = 0 while num != 0: if num % 2 == 0: num = num/2 elif num % 2 != 0 and num % 3 == 0: num = num/3 else: num = num - 1 steps = steps + 1 print(steps) input = 10 stepstozero(input)

You need login to submit your solution