ในปัญหานี้ เราได้รับจำนวนเต็ม 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