View Code of Problem 3494

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            String input = scanner.next();
            String[] nums = input.split("[/+-]");
            int a = Integer.valueOf(nums[0]);
            int b = Integer.valueOf(nums[1]);
            int c = Integer.valueOf(nums[2]);
            int d = Integer.valueOf(nums[3]);
            if (a == c && b == d && input.indexOf('-') > 0){
                System.out.println(0);
                continue;
            }
            int newA = 0;
            if (input.indexOf('-') > 0){
                newA = Math.abs(a*d - b*c);
            }else{
                newA = Math.abs(a*d + b*c);
            }
            int newB = b*d;
            int p = gcd(newA, newB);
            if (input.indexOf('-')>0 && a*d - b*c < 0) System.out.print("-");
            if(newA % newB == 0){
                System.out.println(newA/newB);
            }else{
                System.out.println((newA/p) + "/" + (newB/p));
            }
        }
    }
    public static int gcd(int a, int b){
        if(a%b == 0)return b;
        return gcd(b, a%b);
    }
}

Double click to view unformatted code.


Back to problem 3494