Description
给出两个正整数,计算两个数相加需要多少次进位。
Input
数据有多组,每组包含两个整数,都在int范围内,输入以EOF结尾
Output
一个整数,表示两个数相加需要的进位次数
Sample Input
123 321555 555123456789 987654321
Sample Output
039
HINT
一定要用整数求余相加判断吗?想想有没有简洁的思路。试试用字符串吧,转换思路,分步处理。
[思路很明确,分解每一个数,从最后开始加,如果两数相加大于或等10,那么加接下来两个数的时候就要多加1;同时还要注意9999+1这样的临界情况。好了,话不多说,上代码:]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char x[100],y[100];
while(scanf("%s %s",x,y) != EOF)
{
int lengx = strlen(x);
int lengy = strlen(y);
int i,j,add = 0,plus = 0;
int temp = 0,px = 1,py = 1;
for(i = lengx-1,j = lengy - 1;;i--,j--)
{
if(i >= 0)
temp += x[i] - '0';
else
px = 0;
if(j >= 0)
temp += y[j] - '0';
else
py = 0;
if(temp + plus >= 10)
{plus = 1;add++;}
else
plus = 0;
temp = 0;
if(px == 0 && py == 0)
break;
}
printf("%d\n",add);
}
return 0;
}