C++ 中两个数字的和,其中一个数字用数字数组表示
在这个问题中,我们得到了两个数字,其中一个用数字数组表示。我们的任务是创建一个程序,找到两个数字的和,其中一个数字用数字数组表示。
让我们举个例子来理解这个问题:
Input: n = 213, m[] = {1, 5, 8, }
Output: 371
Explanation: 213 + 158 = 371为了解决这个问题,我们将简单地从数字数组的元素中逐位相加。数字的最低有效位将与数组的第 (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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP