
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the 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
- Related Articles
- Find closest smaller value for every element in array in C++
- Find closest number in array in C++
- Find the number closest to n and divisible by m in C++
- Find the number closest to 10000 and divisible by 30 , 45 , 15.
- Tidy numbers in JavaScript
- Find the Closest Palindrome in C++
- Program to find maximum difference of any number and its next smaller number in Python
- Finding tidy numbers - JavaScript
- Find Number of Array Elements Smaller than a Given Number in Java
- Number of smaller and larger elements - JavaScript
- Find K Closest Elements in C++
- Get the closest number out of an array in JavaScript
- Two numbers are in the ratio 9: 2. If the smaller number is 320, find the larger number.
- Find K Closest Points to the Origin in C++
- Find the closest value of an array in JavaScript

Advertisements