在 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
廣告