(URI) TDA Racional - Solução

import java.io.*;

class Main  {
    static int resultN = 0;
    static int resultD = 0;
           
    public static int mdc(int a, int b) {
        if (b == 0) {
            return a;
        }
        else {
            return mdc(b, a%b);
        }
    }
   
    public static void calc(String op, int n1, int d1, int n2, int d2) {
        switch (op) {
            case "+":
                resultN = (n1*d2 + n2*d1);
                resultD = (d1*d2);
                break;
            case "-":
                resultN = (n1*d2 - n2*d1);
                resultD = (d1*d2);
                break;
            case "*":
                resultN = (n1*n2);
                resultD = (d1*d2);
                break;
            case "/":
                resultN = (n1*d2);
                resultD = (n2*d1);
                break;
            default:
                break;
        }
       
        if (resultN == 0) {
            resultD = 0;
        }
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String entry = br.readLine();
        int n = Integer.parseInt(entry);
       
        for (int i = 0; i < n; i++) {
            String s = br.readLine();
            String[] ss = s.split(" ");
           
            int n1 = Integer.parseInt(ss[0]);
            int d1 = Integer.parseInt(ss[2]);
            int n2 = Integer.parseInt(ss[4]);
            int d2 = Integer.parseInt(ss[6]);

            String op = ss[3];           
            calc(op, n1, d1, n2, d2);

            int div = mdc(resultN, resultD);
      
            if (div < 0) {
                div *= -1;
            }
           
            System.out.println(resultN + "/" + resultD + " = " + resultN/div + "/" + resultD/div);
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução