c014: 10035 - Primary Arithmetic

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=c014

內容

給定兩個正整數,進行加法運算,輸出產生幾次進位。

最後一列有 2 個 0 代表輸入結束。

範例輸入

123 456
555 555
123 594
0 0

範例輸出

No carry operation.
3 carry operations.
1 carry operation.

想法

使用 string 分別存取兩數,開始模擬直式運算(記得考慮各種可能的數字,我卡超久= =)。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int main(){
fastio;
string s1, s2;
int carry, temp;
//int c = 0;
while(cin >> s1){
cin >> s2;
//++c;
//if(c == 2077) cout << s1 << " " << s2;
if(s1 == "0" && s2 == "0") break;
carry = temp = 0;
int index_s1 = s1.length() - 1, index_s2 = s2.length() - 1;
while(index_s1 >= 0 && index_s2 >= 0){
if(((s1[index_s1] - '0') + (s2[index_s2] - '0') + temp) >= 10){
++carry;
temp = 1;
}
else temp = 0;
--index_s1, --index_s2;
}
if(index_s1 >= 0 && s1[index_s1] == '9' && temp == 1){
while(index_s1 >= 0 && s1[index_s1] == '9'){
++carry;
--index_s1;
}
}
else if(index_s2 >= 0 && s2[index_s2] == '9' && temp == 1){
while(index_s2 >= 0 && s2[index_s2] == '9'){
++carry;
--index_s2;
}
}

if(carry == 0) cout << "No carry operation.\n";
else if(carry == 1) cout << "1 carry operation.\n";
else cout << carry << " carry operations.\n";
}
}