2017年12月31日 星期日

[UVa]10035 - Primary Arithmetic(C++)

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=976

Q10035: Primary Arithmetic

在小學時我們都做過加法的運算,就是把2個整數靠右對齊然後,由右至左一位一位相加。如果相加的結果大於等於10就有進位(carry)的情況出現。你的任務就是要判斷2個整數相加時產生了幾次進位的情況。這將幫助小學老師分析加法題目的難度。
Input
每一列測試資料有2個正整數,長度均小於10位。最後一列有2個0代表輸入結束。
Output
每列測試資料輸出該2數相加時產生多少次進位,請參考Sample Output。注意進位超過1次時operation有加s
Sample Input
123 456
555 555
123 594
0 0
Sample Output
No carry operation.
3 carry operations.
1 carry operation.


以上題目翻譯:
http://luckycat.kshs.kh.edu.tw/homework/q10035.htm





#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <stdio.h>
#include <ctype.h>
#include <cmath>
using namespace std;
 
int main() {
 // 10035 - Primary Arithmetic
 string n1, n2;//first num, second num
 while(cin >> n1 >> n2)
 {
  if(n1 == "0" && n2 == "0")
  {
   break;
  }
  else
  {
   int n1_len = n1.size(); //n1的長度
   int n2_len = n2.size(); //n2的長度
   int c = 0;//紀錄進位
   int result = 0; //進位數量
   while(n1_len != 0 && n2_len != 0)
   {
    int x; //相加結果
    int i_n1 = n1[n1_len-1]-'0';
    int i_n2 = n2[n2_len-1]-'0';
    x = i_n1 + i_n2 + c;
    c = 0;
    if(x >= 10)
    {
     c = floor(x/10);
     result++;
    }
    n1_len--;
    n2_len--;
   }
   //如果兩數字長度不同,也要繼續相加計算進位
   if(n1_len > n2_len)
   {
    while(n1_len != 0)
    {
     int x;
     x = n1[n1_len-n2_len-1]-'0' + c;
     c = 0;
     if( x >= 10)
     {
      c = floor(x/10);
      result++;
     }
     n1_len--;
    }
   }
   else if(n2_len > n1_len)
   {
    while(n2_len != 0)
    {
     int x;
     x = n2[n2_len-n1_len-1]-'0' + c;
     c = 0;
     if(x >= 10)
     {
      c = floor(x/10);
      result++;
     }
     n2_len--;
    }
   }
   //輸出
   if(result == 0)
   {
    cout << "No carry operation." << endl;
   }
   else if(result == 1)
   {
 
    cout << result << " carry operation." << endl;
   }
   else
   {
    cout << result << " carry operations." << endl;
   }
  }
 }
 return 0;
}

沒有留言:

張貼留言