C++ Pandigital Number in a Given Base


A number that contains all the digits from 0 to base B is called the Pandigital number in that base. However, some numbers have digits from 1 to 9 and are called zeroless pandigital numbers. Some Examples of pandigital numbers are 0123456789, 0789564312, etc.

In this tutorial, we will discuss a problem where we are given a number and a base, and we need to check whether the number is pandigital in the given base or not, for example −

Input: num = “9651723467380AZ”, base = 10
Output: YES
Explanation: num contains all the digits in the base 10 i.e from 0 to 9, so it is a pandigital number.

Input: num = “130264ABCDE745789”, base = 16
Output: NO
Explanation: num does not contain F(15) which is in the base 16 i.e from 0 to 15, so it is not a pandigital number.

Approach to Find the Solution

To solve this problem, we will use Set and insert each digit in the set because we need to store unique values.

  • Traverse through the string, taking each character at a time.

  • Then check if the element is an integer or alphabet.

  • If it is an alphabet, then add 10 to its position on the alphabet to represent 2-digit.

  • Store the values in the set.

  • After traversing, check whether the size of the set equals to base.

Example

C++ Code for the Above Approach

 
#include<bits/stdc++.h>
using namespace std;
int main(){
    int base = 10;
    char n[] = "9651723467380AZ";
    // Declaring set to store unique values.
    set<int, greater<int> > s;
    // Traversing through the string.
    for (int i = 0; i < strlen(n); i++){
        // Checking if element is Integer.
        if (n[i] >= '0' && n[i] <= '9')
           s.insert(n[i]- '0');
        // Checking if element is alphabet.
        else if (n[i] - 'A' <= base - 11)
           s.insert(n[i] - 'A' + 10) ;
    }
    // Checking if all the digits are present.
    if(s.size()==base)
       cout<< "YES";
    else
        cout<< "NO";
    return 0;
}

Output

YES

Conclusion

In this tutorial, we discussed a problem in which we are given a number and base. We need to find whether the number is pandigital. We discussed a simple approach to solve this problem by inserting values in a set and checking its size with the base. We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.

Updated on: 25-Nov-2021

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements