- Related Questions & Answers
- Print all Prime Quadruplet of a number less than it in C++
- Find a number x such that sum of x and its digits is equal to given n in C++
- Java Program to display a prime number less than the given number
- Find a number x such that sum of x and its digits is equal to given n using C++.
- Print all combinations of points that can compose a given number in C++
- Print all numbers less than N with at-most 2 unique digits in C++
- C++ Program to check if a given number is Lucky (all digits are different)
- Find maximum number that can be formed using digits of a given number in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Print all nodes less than a value x in a Min Heap in C++
- Python - Check if all the values in a list are less than a given value
- Count natural numbers whose all permutation are greater than that number in C++
- Print All Distinct Elements of a given integer array in C++
- Find maximum number of elements such that their absolute difference is less than or equal to 1 in C++
- Find Largest Special Prime which is less than or equal to a given number in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given a number n. Our task is to print the largest number less than n such that all its digits are distinct.

Let’s take an example to understand the problem

Input: n = 2332 Output: 2319

To solve this problem, we reverse the count of the numbers i.e. from n to 0. And check for number with distinct digits, if the current count values satisfy the condition print it and end the loop. Otherwise continue to loop. The max number of times the loop will run is always less than n.

Program to implement our solutions,

#include <bits/stdc++.h> using namespace std; int findDistinctDigitNumber(int n) { for (int i = n - 1; i>=0 ; i--) { int count[10] = { 0 }; int x = i; int count1 = 0, count2 = 0; while (x) { count[x % 10]++; x /= 10; count1++; } for (int j = 0; j < 10; j++) { if (count[j] == 1) count2++; } if (count1 == count2) return i; } } int main() { int n = 44324; cout<<"Number less than "<<n<<" with all digits distinct are : "<<findDistinctDigitNumber(n); return 0; }

Number less than 44324 with all digits distinct are : 43987

Advertisements