Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

math
integer
numbers
bouncy numbers

What are bouncy numbers?

Aaron Xie

A bouncy number is any non-negative integer that is neither increasing nor decreasing.

An increasing integer is any integer in which when going from left to right, the current digit is greater than or equal to the previous digit. For example, 1234 and 14779 are both increasing integers. In contrast, a decreasing integer is any integer in which when going from left to right, the current digit is less than or equal to the previous digit. Some examples of decreasing integers are 6432 and 988743.

svg viewer

Unlike an increasing or decreasing integer, a bouncy number’s digits neither increase or decrease. Rather, they “bounce” between increasing and decreasing. An example is 12435 or 1441. Because the digits both increase and decrease from left to right, they are called bouncy numbers.

For clarification, there are no bouncy numbers before 100, and the first bouncy number is 101. The bouncy numbers between 100 and 120 are 101, 102, 103, 104, 105, 106, 107, 108, 109, and 120.

svg viewer

Write a function to check if a number is bouncy

Python solution:

def is_bouncy(n):
    return sorted(str(n)) != list(str(n)) and sorted(str(n)) != list(str(n))[::-1]

print(is_bouncy(152))

In the solution above, the function returns if the input n is a bouncy number by checking if it is not increasing or decreasing.

  • The str method converts the input n from an integer to a string.

  • The sorted method can convert a string of numbers into a list of the digits in increasing order.

  • The list method splits a string into a list.

  • The [::-1] reverses a list from ["t", "e", "s", "t"] into ["t", "s", "e", "t"]

The string is sorted in both increasing and decreasing order. These sorted strings are compared with the original to check if it is bouncy.

RELATED TAGS

math
integer
numbers
bouncy numbers

CONTRIBUTOR

Aaron Xie
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring