
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
Counting N-Digit Numbers with All Unique Digits in JavaScript
Problem
We are required to write a JavaScript function that takes in a number, let’s say num, as the only argument. The function should count all such numbers that have num digits and all of their digits are unique.
For example, if the input to the function is −
const num = 1;
Then the output should be −
const output = 10;
Output Explanation:
The numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 all have 1 digit and all are unique.
Example
The code for this will be −
const num = 1; const uniqueDigits = (num = 1) => { const dp = [1, 10]; const sum = [1, 11]; for (let i = 2; i <= num; i++) { dp[i] = sum[i - 1] + (10 - i) * (dp[i - 1]); sum[i] = sum[i - 1] + dp[i]; }; return dp[num]; }; console.log(uniqueDigits(num)); console.log(uniqueDigits(2)); console.log(uniqueDigits(3));
Code Explanation:
We have here used Dynamic Programming to keep track of desired numbers.
Output
And the output in the console will be −
10 91 739
Advertisements