Description
给出两个正整数,计算两个数相加需要多少次进位。
Input
数据有多组,每组包含两个整数,都在int范围内,输入以EOF结尾
Output
一个整数,表示两个数相加需要的进位次数
Sample Input
123 321
555 555
123456789 987654321
Sample Output
0
3
9
HINT
一定要用整数求余相加判断吗?想想有没有简洁的思路。试试用字符串吧,转换思路,分步处理。
Append Code
#include<stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int n,m,i,j,s,t,sum,temp;
char a[10000],b[10000];//能不能定义整形数组?
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
while(scanf("%s",a)!=EOF)
{
scanf("%s",b);
sum=0;//sum用来进位次数;
s=0;//若进位,s=1,参与下一位的运算;
n=strlen(a);
m=strlen(b);
for(i=n-1,j=m-1;i>=0||j>=0;i--,j--)//能不能用i>=0&&j>=0?
{
temp=0;//记录两数之和
if(i>=0)
temp+=a[i]-48;
if(j>=0)
temp+=b[j]-48;//这一步是必须的。为什么?
if((temp+s)>=10)
{
sum++;
s=1;
}
else
{
sum+=0;
s=0;
}
}
printf("%d\n",sum);
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
}
return 0;
}