
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number not greater than n where all digits are non-decreasing in python
Suppose we have a number n, we have to find the largest number smaller or equal to n where all digits are non-decreasing.
So, if the input is like n = 221, then the output will be 199.
To solve this, we will follow these steps:
- digits := a list with all digits in n
- bound := null
- for i in range size of digits - 1 down to 0, do
- if digits[i] < digits[i - 1], then
- bound := i
- digits[i - 1] := digits[i - 1] - 1
- if bound is not null, then
- for i in range bound to size of digits, do
- digits[i] := 9
- for i in range bound to size of digits, do
- if digits[i] < digits[i - 1], then
- join each digit in digits to form a number and return it
Let us see the following implementation to get better understanding:
Example Code
class Solution: def solve(self, n): digits = [int(x) for x in str(n)] bound = None for i in range(len(digits) - 1, 0, -1): if digits[i] < digits[i - 1]: bound = i digits[i - 1] -= 1 if bound: for i in range(bound, len(digits)): digits[i] = 9 return int("".join(map(str, digits))) ob = Solution() n = 221 print(ob.solve(n))
Input
221
Output
199
- Related Articles
- Program to find nearest number of n where all digits are odd in python
- Total number of non-decreasing numbers with n digits
- Find the Number of segments where all elements are greater than X using C++
- Python program to print Rows where all its Elements’ frequency is greater than K
- Largest even digit number not greater than N in C++
- Program to count n digit integers where digits are strictly increasing in Python
- Count of Numbers in Range where the number does not contain more than K non zero digits in C++
- C++ program to find longest possible time not greater than T to solve all problems
- Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10
- Program to form smallest number where no two adjacent digits are same in Python
- MongoDB query where all array items are greater than a specified condition?
- Program to find the sum of all digits of given number in Python
- Python Program to Remove all digits before given Number
- How to find the smallest number greater than x in Python?
- C++ program to find in how many bases we can represent the number not greater than M

Advertisements