10404: Primary Arithmetic
Time Limit: 3 secDescription
Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the “carry” operation – in which a 1 is carried from one digit position to be added to the next – to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.Input
Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.Output
For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.Sample Input:
123 456
555 555
123 594
0 0Sample Output:
No carry operation.
3 carry operations.
1 carry operation.
- #include <iostream>
- #include <string>
- #include <algorithm>
- using namespace std;
- int main()
- {
- while(1){
- string a,b;
- cin >> a >> b;
- if(a==“0”&&b==“0”) break;
- int i=0,j=0;
- int count=0;
- reverse(a.begin(),a.end());
- reverse(b.begin(),b.end());
- if(a.size()>b.size()){
- b.resize(a.size()+1,‘0’);
- a.resize(a.size()+1,‘0’);
- }
- if(b.size()>a.size()){
- a.resize(b.size()+1,‘0’);
- b.resize(b.size()+1,‘0’);
- }
- while(i<a.size()&&j<b.size()){
- //cout << (int)(a[i]-‘0’) << ” ” << (int)(b[j]-‘0’) << endl;
- if((int)(a[i]-‘0’)+(int)(b[j]-‘0’)>=10){
- count++;
- a[i+1]=a[i+1]+1;
- }
- i++;j++;
- }
- if(count>1)
- cout << count << ” carry operations.” << endl;
- else if(count==1)
- cout << count << ” carry operation.” << endl;
- else
- cout << “No carry operation.” << endl;
- }
- return 0;
- }
pls:
程式都在cpe系統里鑒定通過了 當然可能coding style未必好 單純供大家參考
如果看不明白 欢迎留言或E-mail我 🙂