POJ 2562 Primary Arithmetic 进位统计

来源:互联网 发布:windows10 内置ubuntu 编辑:程序博客网 时间:2024/06/01 08:16

原题 http://poj.org/problem?id=2562

题目:

Primary Arithmetic
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 11008 Accepted: 4048
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.

思路:

求两个数相加进位了多少次。

此处我们可以效仿高精度的做法,进位的同时ans++。
注意输出格式,进1位和多位的区别,有个s。

代码:

#include <iostream>#include"string.h"#include"cstdio"#include"stdlib.h"#include"algorithm"using namespace std;typedef long long int lint;int main(){    const int N=20;    lint a,b;    while(cin>>a>>b)    {        if(a==0&&b==0)  break;        lint s1[N];        lint s2[N];        memset(s1,0,sizeof(s1));        memset(s2,0,sizeof(s2));        int l1=0;        while(a>0)        {            s1[l1]=a%10;            l1++;            a=a/10;        }        int l2=0;        while(b>0)        {            s2[l2]=b%10;            l2++;            b=b/10;        }        int ans=0;        for(int i=0; i<max(l1,l2)+1; i++)        {            s1[i]=s1[i]+s2[i];            if(s1[i]>=10)            {                s1[i]=s1[i]%10;                s1[i+1]++;                ans++;            }        }        if(ans==0)  printf("No carry operation.\n");        else if(ans==1) printf("1 carry operation.\n");        else        printf("%d carry operations.\n",ans);    }    return 0;}
0 0
原创粉丝点击