
- 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
Count Numbers with Unique Digits in C++
Suppose we have a non-negative integer n. We have to count all numbers with unique digits x, where x is in range 0 to 10^n. So if the number n is 2, then the result will be 91, as we want to find numbers from 0 to 100 without 11, 22, 33, 44, 55, 66, 77, 88, 99.
To solve this, we will follow these steps −
if n is 0, then return 1
n := min of 10 and n
if n is 1, then return 10
ans := 9 and ret := 10
for i in range 2 to n
ans := ans * (9 – i + 2)
ret := ret + ans
return ret
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int countNumbersWithUniqueDigits(int n) { if(n == 0)return 1; n = min(10, n); if(n == 1)return 10; int ans = 9; int ret = 10; for(int i = 2; i<= n; i++){ ans *= (9 - i + 2); ret += ans; } return ret; } }; main(){ Solution ob; cout << (ob.countNumbersWithUniqueDigits(3)); }
Input
3
Output
739
- Related Articles
- Counting n digit Numbers with all unique digits in JavaScript
- Count numbers with same first and last digits in C++
- Print all numbers less than N with at-most 2 unique digits in C++
- C++ code to count number of lucky numbers with k digits
- Numbers With Repeated Digits in C++
- Get the count of unique phone numbers from a column with phone numbers declared as BIGINT type in MySQL
- Count Numbers with N digits which consists of even number of 0's in C++
- Count Numbers with N digits which consists of odd number of 0's in C++
- Program to count number of stepping numbers of n digits in python
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime in C++
- Find Numbers with Even Number of Digits in Python
- Count numbers in range such that digits in it and it's product with q are unequal in C++
- Count by unique key in JavaScript
- Count ways to spell a number with repeated digits in C++
- Fetch Numbers with Even Number of Digits JavaScript

Advertisements