UVa 10035 Primary Arithmetic
解題策略
計算兩數相加總共需要多少次進位,用一般大數加法的技巧,數一下進位次數就行了。//big number a + b int carry_count = 0; for(int i=0;i<MAX_LEN;++i) { a[i] = a[i] + b[i]; if( a[i] > 9 ){ a[i] = a[i] - 10; a[i+1]++; carry_count++; //數數進位幾次... } }
注意
輸出時要注意名詞的單複數,總共有三個狀況0、1、其他,別忘了判斷喔。if(carry_count == 0) printf("No carry operation.\n"); else if (carry_count == 1) printf("1 carry operation.\n"); else printf("%d carry operations.\n", carry_count);
碎碎念
輸出句子最後忘了打句號所以吃了兩次WA....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UVa 10035 Primary Arithmetic | |
* Author: chchwy | |
* Last Modified: 2011/03/05 | |
* Blog: http://chchwy.blogspot.com | |
*/ | |
#include<cstdio> | |
#include<cstring> | |
#include<algorithm> | |
using namespace std; | |
enum { MAX_LEN = 12 }; | |
int to_big_number(char* num) | |
{ | |
// reverse | |
int len = strlen(num); | |
for (int i = 0; i < len / 2; ++i) | |
swap(num[i], num[len - i - 1]); | |
// sub ascii | |
for (int i = 0; i < len; ++i) | |
num[i] = num[i] - '0'; | |
// fill zero | |
for (int i = len; i < MAX_LEN; ++i) | |
num[i] = 0; | |
} | |
int count_carry(char* a, char* b) | |
{ | |
to_big_number(a); | |
to_big_number(b); | |
int carry_counter = 0; | |
for (int i = 0; i < MAX_LEN; ++i) | |
{ | |
a[i] = a[i] + b[i]; | |
if ( a[i] > 9 ) | |
{ | |
a[i] = a[i] - 10; | |
a[i + 1]++; | |
carry_counter++; | |
} | |
} | |
return carry_counter; | |
} | |
int main() | |
{ | |
#ifndef ONLINE_JUDGE | |
freopen("10035.in", "r", stdin); | |
#endif | |
char a[MAX_LEN], b[MAX_LEN]; | |
while (scanf("%s %s ", a, b) == 2) | |
{ | |
if (a[0] == '0' && b[0] == '0') | |
break; | |
int result = count_carry(a, b); | |
if ( result == 0) | |
printf("No carry operation.\n"); | |
else if ( result == 1) | |
printf("1 carry operation.\n"); | |
else | |
printf("%d carry operations.\n", result); | |
} | |
return 0; | |
} |
留言
張貼留言