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