在 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

更新于:2020-1-17

148 浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.