-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
42 lines (29 loc) · 875 Bytes
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Summary:
# Given a number, num, return the shortest amount of steps it would take from 1, to land exactly on that number.
# Description:
# A step is defined as:
# Adding 1 to the number: num += 1
# Doubling the number: num *= 2
# You will always start from the number 1 and you will have to return the shortest count of steps
# it would take to land exactly on that number.
# 1 <= num <= 10000
# Examples:
# num == 3 would return 2 steps:
# 1 -- +1 --> 2: 1 step
# 2 -- +1 --> 3: 2 steps
# 2 steps
# num == 12 would return 4 steps:
# 1 -- +1 --> 2: 1 step
# 2 -- +1 --> 3: 2 steps
# 3 -- x2 --> 6: 3 steps
# 6 -- x2 --> 12: 4 steps
# 4 steps
def shortest_steps_to_num(num):
steps = 0
while num > 1:
if num % 2:
num -= 1
else:
num /= 2
steps += 1
return steps