打印数字的所有子字符串,而无需在C ++中进行任何转换

在这个问题上,我们得到一个整数n。而且,我们必须打印可以形成数字的所有子字符串,但不允许转换字符串,即我们不能将整数转换为字符串或数组。

让我们举个例子来更好地理解这个话题-

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

为了解决这个问题,我们将需要使用数学逻辑。在这里,我们将先打印最高有效位,然后再打印连续位。

算法

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.

示例

#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;
   }
}

输出结果

数字是6789,数字的子字符串是-

6 67 678 6789 7 78 789 8 89 9