Open In App

Self Descriptive Number

Last Updated : 04 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to find all the self-descriptive numbers from 1 to N

A self-descriptive number is an integer n in given base b is b digits long in which each digit at position p (the most significant digit being at position 0 and the least significant at position b – 1) counts how many times a digit p is in n

For example in base 10, 6210001000 is a self descriptive number as there are six 0s, two 1s, one 2 and one 6.
Explanation : 
It is 10 digit number in base 10. 
It has 6 at the position 0 and there are six 0s in 6210001000. 
It has 2 at the position 1 and there are two 1s in 6210001000. 
It has 1 at the position 2 and there is one 2s in 6210001000. 
It has 0 at the position 3 and there are zero 3s in 6210001000. 
It has 0 at the position 4 and there are zero 4s in 6210001000. 
It has 0 at the position 5 and there are zero 5s in 6210001000. 
It has 1 at the position 6 and there is one 6 in 6210001000. 
It has 0 at the position 7 and there are zero 7s in 6210001000. 
It has 0 at the position 8 and there are zero 8s in 6210001000. 
It has 0 at the position 9 and there are zero 9s in 6210001000.
[Source : Wikipedia]

Examples:

Input: N = 10000
Output: 1210 2020
Explanation: From 1 to N only these two numbers are the self-descriptive numbers

Input: N = 10
Output: 
Explanation: There is no self descriptive number in range [1, 10]

 

Here is a program to print all self-descriptive numbers below 100000000. In the below program we have just ignored one fact about the self-descriptive number that it should have as many number of digits as much the base is given.

Description of Program : 
1 . Firstly all the digits get extracted from the outer loop and are stored in a variable b in each iteration. 
2 . Then in the inner loop there is a count on how many times number i (this i is ith index of outer loop) is present in the string. 
3 . Finally that count is compared with the digit present at the ith index stored in variable b. 

C++




// C++ program to print
// all self descriptive
// number below 100000000
#include <iostream>
using namespace std;
 
bool isSelfDescriptiveNumber(int num)
{
    // converting the integer
    // num to string
    string s = to_string(num);
    for (int i = 0;
             i < s.size(); i++)
    {
 
        // Extracting each digit
        // one by one from the
        // string
        char temp_char = s.at(i);
 
        // converting the string
        // (digit) into integer b
        // variable stores the digit
        // present at index 'i'
        int b = temp_char - '0';
 
        // counting how many
        // times the particular
        // digit occur in the
        // whole number "num"
        int count = 0;
        for (int j = 0;
                 j < s.size(); j++)
        {
            // converting string
            // char to integer
            int temp = s.at(j) - '0';
 
            // checking whether it is
            // equal to the index 'i'
            // if it is then increment
            // the count .
            if (temp == i)
            {
                count++;
            }
        }
         
        // If it is not equal
        // it return false .
        if (count != b)
            return false;
    }
    return true;
}
 
// Driver Code
int main()
{
    int N = 1000000;
    for (int i = 1; i <= N; i++)
        if (isSelfDescriptiveNumber(i))
            cout << i << endl;
    return 0;
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Java




// Java program to print all self descriptive
// number below 100000000
public class SelfDescriptive {
 
    public static boolean isSelfDescriptiveNumber(int num)
    {
        // converting the integer num to string
        String s = Integer.toString(num);
        for (int i = 0; i < s.length(); i++) {
 
            // Extracting each digit one by one from the string
            String temp_char = s.charAt(i) + "";
 
            // converting the string (digit) into integer
            // b variable stores the digit present at index 'i'
            int b = Integer.parseInt(temp_char);
 
            // counting how many times the particular digit
            // occur in the whole number "num"
            int count = 0;
            for (int j = 0; j < s.length(); j++) {
                // converting string char to integer
                int temp = Integer.parseInt(s.charAt(j) + "");
 
                // checking whether it is equal to the index 'i'
                // if it is then increment the count .
                if (temp == i) {
                    count++;
                }
            }
 
            // If it is not equal
            // it return false .
            if (count != b)
                return false;
        }
        return true;
    }
 
    public static void main(String[] args)
    {
        int N = 1000000;
        for (int i = 1; i <= N; i++)
            if (isSelfDescriptiveNumber(i))
                System.out.println(i);       
    }
}


Python3




# Python3 program to print
# all self descriptive
# number below 100000000
def isSelfDescriptiveNumber(num):
 
    # Converting the integer
    # num to string
    s = str(num)
     
    for i in range(len(s)):
  
        # Extracting each digit
        # one by one from the
        # string
        temp_char = s[i]
  
        # Converting the string
        # (digit) into integer b
        # variable stores the digit
        # present at index 'i'
        b = ord(temp_char) - ord('0')
  
        # Counting how many
        # times the particular
        # digit occur in the
        # whole number "num"
        count = 0
         
        for j in range(len(s)):
             
            # Converting string
            # char to integer
            temp = ord(s[j]) - ord('0')
  
            # Checking whether it is
            # equal to the index 'i'
            # if it is then increment
            # the count .
            if (temp == i):
                count += 1
                 
        # If it is not equal
        # it return false .
        if (count != b):
            return False
     
    return True
 
# Driver code
if __name__=="__main__":
    N = 1000000
    for i in range(1, N+1):
        if (isSelfDescriptiveNumber(i)):
            print(i)
 
# This code is contributed by rutvik_56


C#




// C# program to print
// all self descriptive
// number below 100000000
using System;
 
class GFG {
    static bool isSelfDescriptiveNumber(int num)
    {
        // converting the integer
        // num to string
        string s = num.ToString();
        for (int i = 0; i < s.Length; i++) {
 
            // Extracting each digit
            // one by one from the
            // string
            string temp_char = s[i] + "";
 
            // converting the string
            // (digit) into integer b
            // variable stores the digit
            // present at index 'i'
            int b = int.Parse(temp_char);
 
            // counting how many
            // times the particular
            // digit occur in the
            // whole number "num"
            int count = 0;
            for (int j = 0; j < s.Length; j++) {
                // converting string
                // char to integer
                int temp = int.Parse(s[j] + "");
 
                // checking whether it is
                // equal to the index 'i'
                // if it is then increment
                // the count .
                if (temp == i) {
                    count++;
                }
            }
 
            // If it is not equal
            // it return false .
            if (count != b)
                return false;
        }
        return true;
    }
 
    // Driver Code
    static void Main()
    {
        int N = 1000000;
        for (int i = 0; i < N; i++)
            if (isSelfDescriptiveNumber(i))
                Console.WriteLine(i);
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


PHP




<?php
// PHP program to print
// all self descriptive
// number below 100000000
 
// Note:
// 100000000 is a huge no so
// it give sometime TLE error
// because its takes compile
// time above 5 sec
function isSelfDescriptiveNumber($num)
{
    // converting the integer
    // num to string
    $s = strval($num);
    for ($i = 0; $i < strlen($s); $i++)
    {
 
        // Extracting each digit
        // one by one from the
        // string
        $temp_char = $s[$i];
 
        // converting the string
        // (digit) into integer b
        // variable stores the digit
        // present at index 'i'
        $b = $temp_char - '0';
 
        // counting how many
        // times the particular
        // digit occur in the
        // whole number "num"
        $count = 0;
        for ($j = 0; $j < strlen($s); $j++)
        {
            // converting string
            // char to integer
            $temp = $s[$j] - '0';
 
            // checking whether it is
            // equal to the index 'i'
            // if it is then increment
            // the count .
            if ($temp == $i)
            {
                $count++;
            }
        }
         
        // If it is not equal
        // it return false .
        if ($count != $b)
            return false;
    }
    return true;
}
 
// Driver Code
$N = 1000000;
for ($i = 0; $i <= $N; $i++)
    if (isSelfDescriptiveNumber($i))
        echo $i."\n";
         
// This code is contributed
// by mits
?>


Javascript




// JavaScript program to print
// all self descriptive
// number below 100000000
 
function isSelfDescriptiveNumber(num)
{
    // converting the integer
    // num to string
    let s = num.toString();
    for (let i = 0;
             i < s.length; i++)
    {
 
        // Extracting each digit
        // one by one from the
        // string
        let temp_char = s[i];
 
        // converting the string
        // (digit) into integer b
        // variable stores the digit
        // present at index 'i'
        let b = temp_char - '0';
 
        // counting how many
        // times the particular
        // digit occur in the
        // whole number "num"
        let count = 0;
        for (let j = 0; j < s.length; j++)
        {
            // converting string
            // char to integer
            let temp = s[j] - '0';
 
            // checking whether it is
            // equal to the index 'i'
            // if it is then increment
            // the count .
            if (temp == i)
            {
                count++;
            }
        }
         
        // If it is not equal
        // it return false .
        if (count != b)
            return false;
    }
    return true;
}
 
// Driver Code
let N = 1000000;
for (let i = 1; i <= N; i++)
    if (isSelfDescriptiveNumber(i))
        console.log(i);
 
// This code is contributed by Nidhi goel


Output

1210
2020
21200

Time Complexity: O( N*len(N)*len(N) )
Auxiliary Space: O(1)

Efficient Approach: The time in above approach can be reduced by storing frequency of each digit in a 10 length array and then checking it consecutively with the corresponding digit.

C++14




#include <bits/stdc++.h>
using namespace std;
 
bool isSelfDescriptiveNumber(int num)
{
    string str=to_string(num);
     
    int i;
     
    int freq[10]={0};
     
    while(num>0)
    {
        freq[num%10]++;
        num/=10;
    }
     
    for(i=0;i<str.length();i++)
        if(freq[i]!=str[i]-'0')
        return 0;
         
    return 1;
}
 
int main()
{
    int N = 1000000;
    for (int i = 1; i <= N; i++)
        if (isSelfDescriptiveNumber(i))
            cout << i << endl;
    return 0;
}


Java




// Java code to implement the approach
import java.util.*;
 
class GFG {
  static boolean isSelfDescriptiveNumber(int num)
  {
    String str = String.valueOf(num);
    int i;
    int[] freq = new int[10];
    for (i = 0; i < 10; i++)
      freq[i] = 0;
 
    while (num > 0) {
      freq[num % 10]++;
      num /= 10;
    }
 
    for (i = 0; i < str.length(); i++)
      if (freq[i] != str.charAt(i) - '0')
        return false;
 
    return true;
  }
 
  public static void main(String[] args)
  {
    int N = 1000000;
    for (int i = 1; i <= N; i++)
      if (isSelfDescriptiveNumber(i))
        System.out.println(i);
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 code to implement the approach
 
 
# Function to check if the number is self descriptive
def isSelfDescriptiveNumber(num):
 
    str_ = str(num)
 
    # A frequency table for all the digits
    freq = [0 for _ in range(10)]
 
    # Building the frequency table for the number
    while (num > 0):
        freq[num % 10] += 1
        num //= 10
 
    for i in range(len(str_)):
        if (freq[i] != int(str_[i])):
            return 0
 
    return 1
 
 
# Driver Code
N = 1000000
for i in range(1, 1 + N):
    if (isSelfDescriptiveNumber(i)):
        print(i)
 
 
# This code is contributed by phasing17


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
  static bool isSelfDescriptiveNumber(int num)
  {
    string str = Convert.ToString(num);
    int i;
    int[] freq = new int[10];
    for (i = 0; i < 10; i++)
      freq[i] = 0;
 
    while (num > 0) {
      freq[num % 10]++;
      num /= 10;
    }
 
    for (i = 0; i < str.Length; i++)
      if (freq[i] != str[i] - '0')
        return false;
 
    return true;
  }
 
  public static void Main(string[] args)
  {
    int N = 1000000;
    for (int i = 1; i <= N; i++)
      if (isSelfDescriptiveNumber(i))
        Console.WriteLine(i);
  }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript code to implement the approach
 
function isSelfDescriptiveNumber(num)
{
    let str = num.toString();
 
    let i;
 
    let freq = new Array(10).fill(0);
 
    while (num > 0) {
        freq[num % 10]++;
        num = Math.floor(num / 10);
    }
 
    for (i = 0; i < str.length; i++)
        if (freq[i] != parseInt(str[i]))
            return 0;
 
    return 1;
}
 
let N = 1000000;
for (var i = 1; i <= N; i++)
    if (isSelfDescriptiveNumber(i))
        console.log(i);
 
// This code is contributed by phasing17


Output

1210
2020
21200

Time Complexity: O( N*len(N) )
Auxiliary Space: O(1)
 



Previous Article
Next Article

Similar Reads

Inversion count in Array Using Self-Balancing BST
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If an array is already sorted then the inversion count is 0. If an array is sorted in the reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] &gt; a[j] and i &lt; j. For simplicity, we may assume that all e
19 min read
Self-Balancing Binary Search Trees
Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average. Examples: The most common examples of self-balan
4 min read
Find the centroid of a non-self-intersecting closed Polygon
Given N vertices of the polygon, the task is to find the centroid of the polygonExamples: Input: ar = {{0, 0}, {0, 8}, {8, 8}, {8, 0}} Output: {Cx, Cy} = {4, 4} Input: ar = {{1, 2}, {3, -4}, {6, -7}} Output: {Cx, Cy} = {3.33, -3} Approach: The centroid of a non-self-intersecting closed polygon defined by n vertices (x0, y0), (x1, y1), ..., (xn-1, y
5 min read
Why You Should Become a Self-Taught Programmer?
You may have heard about Jack Dorsey (Twitter), Mark Zuckerberg (Facebook), Kevin Systrom (Instagram) and many others. Right, these are one of the top programmers and tech enthusiasts who are currently ruling the world. But, have you ever thought that what made them so accomplished and proficient in the world of programming? No, it is not any colle
8 min read
Self Numbers
A Number N is said to be Self Number if it can not be written as M + sum of digits of M for any M.The first few Self numbers are: 1, 3, 5, 7, 9, 20, 31, 42................ Check if N is a Self number Given an integer N, the task is to find if this number is Self number or not. Examples: Input: N = 3 Output: Yes Explanation: 1 + sumofDigits(1) = 2 2
5 min read
Self Balancing BST in JavaScript
A self-balancing binary search tree (BST) is a type of binary search tree that automatically keeps its height balanced in order to guarantee that operations such as searching, inserting, and deleting elements in the tree take less time on average. How do self-balancing BSTs maintain height balance? Self-balancing binary search trees (BSTs) maintain
11 min read
Find the Kth smallest term in self cross-product Array
Given an array arr[] of n elements, find the Kth lexicographically smallest in its corresponding cross-product array. For an array arr of n elements, the cross product of the array, cp_arr, is defined as cp_arr = {{arr[i], arr[j}} for all 0 &lt; i, j &lt; n. Examples: Input: n = 3, K = 7, arr[] = {3, 1, 2} Output: [3, 1]Explanation: [3, 1, 2] * [3,
8 min read
Self Organizing List : Move to Front Method
Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times.  So, a s
10 min read
Self Organizing List : Count Method
Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times.  So, a s
11 min read
Self Organizing List | Set 1 (Introduction)
The worst case search time for a sorted linked list is O(n). With a Balanced Binary Search Tree, we can skip almost half of the nodes after one comparison with root. For a sorted array, we have random access and we can apply Binary Search on arrays. One idea to make search faster for Linked Lists is Skip List. Another idea (which is discussed in th
3 min read
Practice Tags :