
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
Find Closest and Smaller Tidy Number in C++
Suppose we have a number n, we have to find the closest and smaller tidy number of n. So a number is called tidy number, if all of its digits are sorted in non-decreasing order. So if the number is 45000, then the nearest and smaller tidy number will be 44999.
To solve this problem, we will traverse the number from end, when the tidy property is violated, then we reduce digit by 1, and make all subsequent digit as 9.
Example
#include<iostream> using namespace std; string tidyNum(string number) { for (int i = number.length()-2; i >= 0; i--) { if (number[i] > number[i+1]) { number[i]--; for (int j=i+1; j<number.length(); j++) number[j] = '9'; } } return number; } int main() { string str = "45000"; string num = tidyNum(str); cout << "The tidy number is: " << num; }
Output
The tidy number is: 44999
Advertisements