洛谷——P1572 计算分数

P1572 计算分数

 

模拟+字符串

 

注意有两位数的情况以及负数情况

 

#include<bits/stdc++.h>

using namespace std;

string s;
int a[1006],b[1006],tot,kp[1006];

int gcd(int x,int y) {
    return !y?x:gcd(y,x%y);
}

int main() {
    cin>>s;
    int k=0;
    ++tot;
    while(1) {
        if(s[k]=='/') break;
        if(k==s.length()) break;
        a[tot]=a[tot]*10+s[k]-'0';
        k++;
    }
    for(int i=0; i<s.length(); i++) {
        if(s[i]=='/') {
            int k=i+1;
            while(1) {
                if(s[k]=='+'||s[k]=='-') break;
                if(k==s.length()) break;
                b[tot]=b[tot]*10+s[k]-'0';
                k++;
            }
        }
        if(s[i]=='+') kp[tot]=1;
        if(s[i]=='-') kp[tot]=0;
        if(s[i]=='+'||s[i]=='-') {
            ++tot;
            int k=i+1;
            while(1) {
                if(s[k]=='/') break;
                if(k==s.length()) break;
                a[tot]=a[tot]*10+s[k]-'0';
                k++;
            }
        }
    }
    b[0]=1;
    for(int i=1; i<=tot; i++)
        b[0]=(b[0]*b[i])/gcd(b[0],b[i]);
    kp[0]=1;
    for(int i=1; i<=tot; i++) {
        a[0]=a[0]+(!kp[i-1]?-1:1)*(a[i]*b[0])/b[i];
    }
    int x=b[0]/gcd(a[0],b[0]),y=a[0]/gcd(a[0],b[0]);
    if(x==1) printf("%d\n",y);
    else if(x==-1) printf("-%d\n",y<0?-y:y);
    else if(x<0) printf("%d/%d\n",-y,-x);
    else printf("%d/%d\n",a[0]/gcd(a[0],b[0]),b[0]/gcd(a[0],b[0]));
    return 0;
}

 

posted @ 2018-09-10 21:42  清风我已逝  阅读(268)  评论(0编辑  收藏  举报