Print all substring of a number without any conversion in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer n. And we have to print all substrings of a number that can be formed but converting the string are not allowed i.e. we cannot convert an integer into string or array.

Let’s take an example to understand the topic better −

Input: number =5678
Output: 5, 56, 567, 5678, 6, 67, 678, 7, 78, 8

In order to solve this problem, we will need to use mathematical logic. Here, we will print the most significant bit first, then successive bits are printed.

Algorithm

Step1: Take a 10’s power number based on the number of digits.
Step2: print values recursively and divide the number by 10 and repeat until the number becomes 0.
Step3: Eliminate the MSB of the number and repeat step 2 with this number.
Step4: Repeat till the number becomes 0.

Example

 Live Demo

#include <iostream>
#include<math.h>
using namespace std;
void printSubNumbers(int n) ;
int main(){
   int n = 6789;
   cout<<"The number is "<<n<<" and the substring of number are :\n";
   printSubNumbers(n);
   return 0;
}
void printSubNumbers(int n){
   int s = log10(n);
   int d = (int)(pow(10, s) + 0.5);
   int k = d;
   while (n) {
      while (d) {
         cout<<(n / d)<<" ";
         d = d / 10;
      }
      n = n % k;
      k = k / 10;
      d = k;
   }
}

Output

The number is 6789 and the substring of a number are −

6 67 678 6789 7 78 789 8 89 9
raja
Published on 17-Jan-2020 10:16:46
Advertisements