MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / fractionAddition

Method fractionAddition

FractionAdditionSubstraction.java:2–39  ·  view source on GitHub ↗
(String expression)

Source from the content-addressed store, hash-verified

1class Solution {
2 public String fractionAddition(String expression) {
3 int num=0;
4 int den=1;
5 int n = expression.length();
6 int i=0;
7 while(i<n){
8 int curNum=0;
9 int curDen=0;
10 boolean isNeg = false;
11 char ch = expression.charAt(i);
12 if(ch == '+' || ch == '-'){
13 if(ch=='-'){
14 isNeg = true;
15 }
16 i++;
17 }
18 //form the num
19 int start=i;
20 while(Character.isDigit(expression.charAt(i))){
21 i++;
22 }
23 curNum = Integer.parseInt(expression.substring(start,i));
24 if(isNeg) curNum*=-1;
25 i++; //skip /
26 //form the den
27 start=i;
28 while(i<n && Character.isDigit(expression.charAt(i))){
29 i++;
30 }
31 curDen = Integer.parseInt(expression.substring(start,i));
32 num = num * curDen + curNum * den;
33 den *= curDen;
34 }
35 int gcd = Math.abs(getGCD(num,den));
36 num/=gcd;
37 den/=gcd;
38 return num + "/" + den;
39 }
40 public int getGCD(int a, int b){
41 if(a==0) return b;
42 return getGCD(b%a,a);

Callers

nothing calls this directly

Calls 1

getGCDMethod · 0.95

Tested by

no test coverage detected