Easy Understand Java Solution using class fraction


  • 0
    D
    private class Fraction {
    		long a, b;
    
    		Fraction(long a, long b) {
    			if (b < 0) {
    				a = -a;
    				b = -b;
    			}
    			long g = gcd(Math.abs(a), Math.abs(b));
    			a /= g;
    			b /= g;
    			this.a = a;
    			this.b = b;
    		}
    
    		private long gcd(long a, long b) {
    			return b == 0 ? a : gcd(b, a % b);
    		}
    
    		private Fraction add(Fraction that) {
    			return new Fraction(a * that.b + b * that.a, b * that.b);
    		}
    
    		@Override
    		public String toString() {
    			return a + "/" + b;
    		}
    	}
    	
    	public String fractionAddition(String expression) {
    		String[] exps = expression.replace("-", "+-").split("\\+");
    		Fraction zero = new Fraction(0, 1);
    		for (int i = 0; i < exps.length; i++){
    			if (exps[i].isEmpty()) continue;
    			long a = Long.parseLong(exps[i].split("/")[0]);
    			long b = Long.parseLong(exps[i].split("/")[1]);
    			zero = zero.add(new Fraction(a, b));
    		}
    		return zero.toString();
    	}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.