UVa 10035 – Primary Arithmetic
In elementary school, we all learned addition, which involves aligning two integers to the right and then adding digit by digit from right to left. If the sum of the digits is greater than or equal to 10, there will be a carry-over situation.
Your task is to determine how many carry-overs occur when adding two integers. This will help elementary school teachers analyze the difficulty of addition problems.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF 輸入,每一列測試資料有 2 個正整數,長度均小於 10 位。最後一列有 2 個 0 代表輸入結束。 | 每列測試資料輸出該 2 數相加時產生多少次進位。注意進位超過 1 次時 operation 要加 s。 |
123 456 555 555 123 594 0 0 | No carry operation. 3 carry operations. 1 carry operation. |
Thought Process
You can use strings to store numbers and perform calculations in the most traditional vertical format. You can start by reversing both strings so that when you run the for loop, you can iterate from left to right.
Sample Code-ZeroJudge C014: Primary Arithmetic
#include <iostream>
#include <algorithm>
using namespace std;
int toint(char a)
{
return int(a - '0');
}
void output(int ans)
{
if (ans == 0) cout << "No carry operation.\n";
else if (ans == 1) cout << "1 carry operation.\n";
else cout << ans << " carry operations.\n";
}
int main() {
cin.sync_with_stdio(false);
cin.tie(nullptr);
int a, b;
while (cin >> a >> b)
{
if (a == 0 && b == 0) break;
else
{
if (a > b) swap(a, b);
int count = 0;
string one = to_string(a);
string two = to_string(b);
reverse(one.begin(), one.end());
reverse(two.begin(), two.end());
int carry = 0, ans = 0;
for (int i = 0; i<max(one.length(), two.length()); i++)
{
int sum = carry;
if(i < (int) one.size()) {
sum += one[i] - '0';
}
if(i < (int) two.size()) {
sum += two[i] - '0';
}
carry = (sum >= 10);
ans += carry;
}
output(ans);
}
}
}
//ZeroJudge C014
//Dr. SeanXD