Primary Arithmetic

Primary Arithmetic

时间: 1ms        内存:64M

描述:

Children are taught to add multi-digit numbers from right to left, one digit at a time. Many find the ``carry" operation, where a 1 is carried from one digit position 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, compute the number of carry operations that result from adding the two numbers and print them in the format shown below.

示例输入:

123 456
555 555
123 594
0 0

示例输出:

No carry operation.
3 carry operations.
1 carry operation.

提示:

参考答案(内存最优[752]):

#include <stdio.h>
#include <string.h>

void exchange( char a[], int b[] );

int main()
{
	int a[20], b[20];
	char c[20], d[20];
	int i;
	int count;
	int t1, t2;

	while( scanf("%s%*c%s", c, d) != EOF )
	{
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		count = 0;
		if( c[0] == '0' && d[0] == '0' )
		{
			break;
		}

		exchange(c, a);
		exchange(d, b);

		t1 = strlen(c);
		t2 = strlen(d);

		t1 = t2 > t1 ? t2 : t1;

		for( i = 0; i < t1+1; i++ )
		{
			if( a[i] + b[i] > 9 )
			{
				a[i+1] += 1;
				count++;
			}
		}

	if(count == 0) 
	{
		 printf("No carry operation.\n");
	}
    if(count == 1)
	{
		printf("1 carry operation.\n");
	}
    if(count > 1)
	{
      printf("%d carry operations.\n",count);
	}
	
	}



	return 0;
}

void exchange( char a[], int b[] )
{
	int i;

	for( i= strlen(a)-1 ; i >= 0; i-- )
	{
		b[strlen(a)-1-i] = a[i] - '0';
	}

}

参考答案(时间最优[0]):

#include <cstdio>
int main()
{
    long int a, b;
    int carry, c;
    while (scanf("%ld%ld", &a, &b) , a + b)
    {
        carry = c = 0;
        while (a || b)
        {
            c = (a % 10 + b % 10 + c) > 9 ? 1 : 0;
            carry += c;
            a /= 10;
            b /= 10;
        }
        if (carry == 0)puts("No carry operation.");
        else if (carry == 1)puts("1 carry operation.");
        else printf("%d carry operations.\n", carry);
    }
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注