【HDOJ】1717 小数化分数2

简单字符串处理。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cmath>
 4 #include <ctype.h>
 5 
 6 #define MAXN 25
 7 char str[MAXN];
 8 int ten[15];
 9 
10 int gcd(int m, int n) {
11     if (m == 0)
12         return n;
13     if (m > n)
14         return gcd(n, m);
15     else
16         return gcd(m, n%m);
17 }
18 
19 int main() {
20     int t, a, b, ka, kb, n, m;
21     int i, k;
22     bool hascircle;
23 
24     ten[0] = 1;
25     for (i=1; i<15; ++i)
26         ten[i] = ten[i-1]*10;
27 
28     scanf("%d", &t);
29     while (t--) {
30         scanf("%s", str);
31         a = b = 0;
32         ka = kb = 0;
33         hascircle = false;
34         // ignore 0.
35         for (i=2; str[i]; ++i) {
36             if (str[i] == '(') {
37                 hascircle = true;
38             } else if ( isdigit(str[i]) ) {
39                 if (hascircle) {
40                     b = b*10+str[i]-'0';
41                     kb++;
42                 } else {
43                     a = a*10+str[i]-'0';
44                     ka++;
45                 }
46             }
47         }
48         // a: integer for not circle part, b: integer for circle part
49         // ka: number of bits for a, kb: number of bits for b
50         // result = m/n;
51         if (kb) {
52             n = ten[ka+kb] - ten[ka];
53             m = a*ten[kb]+b-a;
54         } else {
55             n = ten[ka];
56             m = a;
57         }
58         k = gcd(m, n);
59         printf("%d/%d\n", m/k, n/k);
60 #ifndef ONLINE_JUDGE
61         fflush(stdout);
62 #endif
63     }
64 
65     return 0;
66 }

 

posted on 2014-09-15 22:13  Bombe  阅读(220)  评论(0编辑  收藏  举报

导航