两个数字的和,其中一个数字表示为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 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短