1638 - Primary Arithmetic
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.
Examples
Input
555 445 4325 5996 8 1 0 0
Output
1 carry operation. 3 carry operations. NO carry operation.
Hint
只是按位相加,1+999只有1个进位!!--不考虑进位带来新的进位。
Solution C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { unsigned int a; unsigned int b; while(scanf("%d%d",&a,&b) != EOF){ if(a==0 && b==0)break; char temp2[20], temp1[20]; sprintf(temp1,"%d",a); sprintf(temp2,"%d",b); int ans = 0; for(int i = strlen(temp1),j = strlen(temp2);i >= 0&&j >= 0; i--, j--){ if(temp1[i]-'0' + temp2[j]-'0' >= 10)ans++; } if(ans==1) printf("%d carry operation.\n",ans); if(ans>1) printf("%d carry operations.\n",ans); if(ans==0) printf("NO carry operation.\n"); } return 0; }
Solution C++
#include "stdio.h" int main() { int a,b,c; while(1) { int x = 0; scanf("%d%d",&a,&b); if(a == 0 && b == 0) break; while(a>0 && b>0) { if(a%10 + b%10 >= 10) x++;//只是按位相加,1+999只有1个进位!!--不考虑进位带来新的进位。 a /= 10; b /= 10; } if(x == 0) printf("NO carry operation.\n"); else if(x == 1) printf("1 carry operation.\n"); else printf("%d carry operations.\n",x); } return 0; }
Hint
只是按位相加,1+999只有1个进位!!--不考虑进位带来新的进位。