题目描述
小明很喜欢做a+b,他但经常忘记进位,所以他算88+12=90,而不是100。 现在你给了小明一些a+b的算式,请问他算出来会是什么?
输入
第一行是一个整数K,表示样例的个数。 每个样例占一行,为两个整数a,b,0≤a,b≤1e9。
输出
每行输出一个样例的结果,不要输出前导0。
样例输入
3 1 2 5 6 55 55样例输出
3 1 0
解题思路:模拟手算加法,个位和个位对齐,十位和十位对齐......;先算“突出”来那一部分的,然后算需要 两两相加 的部分,这时就把 相加和 模10(取消进位),两步完成,直接交题。
AC代码:
1、字符串类型输入
- #include
- #include
-
- int K,a,b,flag,i,j;
- int lenA,lenB,len,ans;
- char strA[12],strB[12];
-
- int main()
- {
- scanf("%d",&K);
- while ( K --)
- {
- ans = 0;
- scanf("%s %s",strA,strB);
- lenA = strlen(strA), lenB = strlen(strB);
- flag = 1, len = lenB-lenA; //默认数字 b>a
- if (lenA > lenB) {flag = 0, len = lenA-lenB;} //不然 令flag=0
- if (flag) // b>a的情况
- {
- for (i = 0; i < len; i ++)
- ans = ans*10 + (strB[i]-'0');
- for (j = 0; j < lenA; j ++,i ++)
- ans = ans*10 + ((strB[i]-'0') + (strA[j]-'0'))%10;
- }
- else // a>b的情况
- {
- for (i = 0; i < len; i ++)
- ans = ans*10 + (strA[i]-'0');
- for (j = 0; j < lenB; j ++,i ++)
- ans = ans*10 + ((strA[i]-'0') + (strB[j]-'0'))%10;
- }
- printf("%d\n",ans);
- }
- }
2、整数类型输入(以前的代码)
- #include
-
- int max(int x,int y)
- {
- if (x < y) x = y;
- return x;
- }
-
- int main()
- {
- int K;
- int a,b;
- scanf("%d",&K);
- while ( K --)
- {
- int a1[15] = {0};
- int b1[15] = {0};
- int c1[15] = {0};
- int aw,bw;
- scanf("%d %d",&a,&b);
- for (aw = 1; a > 0; aw ++)
- {
- a1[aw] = a%10;
- a /= 10;
- // printf("a1[%d] = %d\n",aw,a1[aw]);
- }
- for (bw = 1; b > 0; bw ++)
- {
- b1[bw] = b%10;
- b /= 10;
- // printf("b1[%d] = %d\n",bw,b1[bw]);
- }
- int m = max(aw,bw);
- // printf("m = %d\n",m);
- for (int i = 1; i < m; i ++)
- {
- c1[i] = a1[i] + b1[i];
- if (c1[i] > 9) c1[i] -= 10;
- // printf("c1[%d] = %d\n",i,c1[i]);
- }
-
- int ans = 0;
- for (int j = m-1; j >= 1; j --)
- {
- ans = ans*10 + c1[j];
- }
- printf("%d\n",ans);
- }
- return 0;
- }