我想改变条件,但我不能



问题:教孩子们从右到左添加多位数,一次添加一位数。许多人发现"进位"操作是一个重大挑战,即1从一个数字位置进位到下一个数字。你的工作是计算一组加法题的进位运算次数,以便教育工作者评估他们的难度。

输入:每行输入包含两个小于10位的无符号整数。最后一行输入包含"0"0。

输入示例:对于除最后一行以外的每一行输入,计算两个数字相加后的进位运算次数,并按以下格式打印。

这是满足小于10位输入的原始代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
int main(void){
unsigned int n1, n2, remain_n1, remain_n2, carry;
while(1)
{
std::cin >> n1 >> n2;
if(n1 == 0 && n2 == 0)
break;
int carry = 0;
int count = 0;
int sum = 0;
while(n1 != 0 || n2 != 0)
{
remain_n1 = n1 % 10;        
remain_n2 = n2 % 10;         
if(carry == 1)             
remain_n1++;          

sum = remain_n1 + remain_n2;       
carry = 0;
if(sum >= 10){                     
carry = carry + 1;                         
count = count + 1;                       
}
n1 = n1 / 10;                          
n2 = n2 / 10;                              
}
if(count == 0)
std::cout << "No carry operation." << std::endl;
else if(count == 1)
std::cout << count << " " << "carry operation" << std::endl;
else
std::cout << count << " " << "carry operations" << std::endl;
}
return 0;
}

问题输入不到10位,但无论输入什么,我都想更改以满足条件。这是我的密码。我应该如何解决这个问题?

std:;string n1, n2;
while(1){
std:;cint >> n1 >> n2;
if(n1 == "0" && n2 == "0")
break;
int max_len = n1.szie();
if (max_len < n2.size())
max_len = n2.size();
int nn1[max_len] - {0);
int nn2[max_len] = {0};
for(int i = 0; i < n1.size(); i++)
nn1[max_len - n1.size() + i]; = n1[i] - '0'; 
}

您不需要任何额外的数字存储,您可以直接使用字符串的数字,并在进行转换时进行转换。

也许是这样的:

std::cin >> a >> b;
int carry = 0;
int count = 0;
// Iterate in reverse.
for (auto ia = a.rbegin(), ib = b.rbegin(); ia != a.rend() && ib != b.rend(); ++ia, ++ib)
{
int sum = (*ia - '0') + (*ib - '0') + carry;
carry = sum >= 10;
count += carry;
}

最新更新