I am trying to find the minimum number of steps it takes to reach "1" with the following:
For each step, I can take one of the following steps:
The function will be passed a string representing a positive integer. My function appears to be working but I am failing on some edge cases, but I am not sure how to find the edge cases that would cause a failure.
n = int(n)
count = 0
while n > 1:
if int(n) & int(n-1) == 0:
count += len(str(bin(n))) - 3
break
if n % 2 == 0:
n /= 2
else:
if (n - 1) % 4 == 0:
n -= 1
else:
n += 1
count += 1
return count
Here are a couple of examples of passed tests:
Input: solution.solution('15') Output: 5 (15 -> 16 -> 8 -> 4 -> 2 -> 1)
Input: solution.solution('4') Output: 2 (4 -> 2 -> 1)
Just write a naive solution and compare the results for a bunch of inputs.
def elliott(n):
n = int(n)
count = 0
while n > 1:
if int(n) & int(n-1) == 0:
count += len(str(bin(n))) - 3
break
if n % 2 == 0:
n //= 2
else:
if (n - 1) % 4 == 0:
n -= 1
else:
n += 1
count += 1
return count
def naive(n):
reached = {int(n)}
steps = 0
while 1 not in reached:
for x in reached.copy():
reached |= {x - 1, x + 1}
if x % 2 == 0:
reached.add(x // 2)
steps += 1
return steps
for n in range(1, 20):
x, y = elliott(n), naive(n)
if x != y:
print(n, x, y)
Output:
3 3 2
6 4 3
11 6 5
12 5 4
13 6 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.