ในปัญหานี้ เราได้รับตัวเลขสองตัว จากที่หนึ่งแสดงโดยใช้อาร์เรย์ของตัวเลข งานของเราคือสร้างโปรแกรมที่จะหาผลรวมของตัวเลขสองตัวโดยที่ตัวหนึ่งแสดงเป็นอาร์เรย์ของตัวเลข
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
Input: n = 213, m[] = {1, 5, 8, }
Output: 371
Explanation: 213 + 158 = 371 เพื่อแก้ปัญหานี้ เราจะเพียงแค่ตัวเลขจากตัวเลขซึ่งเป็นองค์ประกอบของอาร์เรย์ lsb ของตัวเลขถูกเพิ่มไปยังองค์ประกอบ (n-1) ของอาร์เรย์ การแครี่จะถูกเผยแพร่ในครั้งต่อไป
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#include <iostream>
using namespace std;
void addNumbers(int n, int size, int *m){
int carry = 0;
int sum = 0;
for(int i = size-1; i >= 0; i--){
sum = (n%10) + m[i] + carry;
n /= 10;
carry = sum/10;
m[i] = sum%10;
}
}
int main() {
int n= 679;
int m[] = {1, 9, 5, 7, 1, 9};
int size = sizeof(m)/sizeof(m[0]);
cout<<"The sum of two numbers where one number is represented as array of digits is ";
addNumbers(n, size, m);
for(int i = 0; i < size; i++)
cout<<m[i];
} ผลลัพธ์
The sum of two numbers where one number is represented as array of digits is 196398