Categories
CPE 程式解答

10404: Primary Arithmetic

10404: Primary Arithmetic
Time Limit: 3 sec

Description
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 0

Sample Output:
No carry operation.
3 carry operations.
1 carry operation.

  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     while(1){
  10.         string a,b;
  11.         cin >> a >> b;
  12.         if(a=="0"&&b=="0") break;
  13.         int i=0,j=0;
  14.         int count=0;
  15.         reverse(a.begin(),a.end());
  16.         reverse(b.begin(),b.end());
  17.         if(a.size()>b.size()){
  18.             b.resize(a.size()+1,'0');
  19.             a.resize(a.size()+1,'0');
  20.         }
  21.         if(b.size()>a.size()){
  22.             a.resize(b.size()+1,'0');
  23.             b.resize(b.size()+1,'0');
  24.         }
  25.         while(i<a.size()&&j<b.size()){
  26.             //cout << (int)(a[i]-'0') << " " << (int)(b[j]-'0') << endl;
  27.             if((int)(a[i]-'0')+(int)(b[j]-'0')>=10){
  28.                 count++;
  29.                 a[i+1]=a[i+1]+1;
  30.             }
  31.             i++;j++;
  32.         }
  33.         if(count>1)
  34.             cout << count << " carry operations." << endl;
  35.         else if(count==1)
  36.             cout << count << " carry operation." << endl;
  37.         else
  38.             cout << "No carry operation." << endl;
  39.     }
  40.     return 0;
  41. }

pls:
程式都在cpe系統里鑒定通過了 當然可能coding style未必好 單純供大家參考
如果看不明白 欢迎留言或E-mail我 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.