Bouncy numbers
Problem 112
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
def is_bouncy_string(n):
inc = False
dec = False
s = str(n)
for i in range(len(s) - 1):
if s[i + 1] > s[i]:
inc = True
elif s[i + 1] < s[i]:
dec = True
if inc and dec:
return True
return False
def is_bouncy(n):
inc = False
dec = False
last = n % 10
n /= 10
while n > 0:
tmp = n % 10
n /= 10
if tmp < last:
inc = True
elif tmp > last:
dec = True
last = tmp
if inc and dec:
return True
return False
def run():
target = 100
i = 1
non_bouncy = 1
while non_bouncy * target != i:
i += 1
if not is_bouncy(i):
non_bouncy += 1
return i