两个数字的和,其中一个数字表示为C ++中的数字数组
在这个问题中,我们给了两个数字,其中一个用数字数组表示。我们的任务是创建一个程序,该程序将查找两个数字的和,其中一个数字表示为数字数组。
让我们举个例子来了解这个问题,
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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短