
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Monotone Increasing Digits in C++
Suppose we have a non-negative integer N, we have to find the largest number that is less than or equal to N with monotone increasing digits. We know that an integer has monotone increasing digits if and only if each pair of adjacent digits’ x and y satisfy x <= y.) So if the input is like 332, then the result will be 299.
To solve this, we will follow these steps −
- s := N as string, i := 1, n := size of s
- while i < n and s[i] >= s[i – 1]
- increase i by 1
- if i < n
- while i > 0 and s[i – 1] > s[i], then
- decrease i by 1
- decrease s[i] by 1
- while i > 0 and s[i – 1] > s[i], then
- for j in range i + 1 to n
- s[j] := ‘9’
- return s as number
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int monotoneIncreasingDigits(int N) { string s = to_string(N); int i = 1; int n = s.size(); while(i < n && s[i] >= s[i - 1]) i++; if( i < n) while(i > 0 && s[i - 1] > s[i]){ i--; s[i]--; } for(int j = i + 1; j < n; j++)s[j] = '9'; return stoi(s); } }; main(){ Solution ob; cout << (ob.monotoneIncreasingDigits(332)); }
Input
332
Output
299
Advertisements