(hnust 1208)Problem C: Primary Arithmetic(水題)

feng_zhiyu發表於2017-08-08

時間限制: 1 Sec 記憶體限制: 128 MB
提交: 4 解決: 3
[提交][狀態][討論版]
題目描述
Problem C: Primary Arithmetic
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.

Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0. 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.

輸入
輸出
樣例輸入
123 456
555 555
123 594
0 0
樣例輸出
No carry operation.
3 carry operations.
1 carry operation.

題意:給兩個不超過10位的數,相加,問有多少次進位?
分析:模擬, 注意No 和1的時候沒有s !!!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
const double INF=0x3f3f3f3f+1.0;
const double eps=1e-6;
const double PI=2.0*acos(0.0);
typedef long long LL;
const int N=15;
int a[N],b[N],ans;
int main()
{
    char str1[N],str2[N];
    while(~scanf("%s%s",str1,str2))
    {
        if(str1[0]=='0'&&str2[0]=='0') break;
        ans=0;
        mem(a,0),mem(b,0);
        int len1,len2,len;
//      printf("%s  %s\n",str1+1,str2+1);
        len1=strlen(str1),len2=strlen(str2);
        str1[len1]='\0',str2[len2]='\0';
//      printf("%d %d\n",len1,len2);
        for(int i=len1-1,j=0; i>=0; i--,j++)
            a[j]=str1[i]-'0';
        for(int i=len2-1,j=0; i>=0; i--,j++)
            b[j]=str2[i]-'0';
        len=max(len1,len2);
        for(int i=0; i<len; i++)
        {
            a[i]+=b[i];
            if(a[i]>9)
            {
                ans++;
                a[i+1]+=(a[i]/10);
                a[i]%=10;
            }
        }
        if(ans)
        {
            if(ans==1) printf("1 carry operation.\n");
            else printf("%d carry operations.\n",ans);
        }
        else printf("No carry operation.\n");
    }
    return 0;
}

相關文章