-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathFractionAdditionSubstraction.java
More file actions
44 lines (44 loc) · 1.24 KB
/
FractionAdditionSubstraction.java
File metadata and controls
44 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public String fractionAddition(String expression) {
int num=0;
int den=1;
int n = expression.length();
int i=0;
while(i<n){
int curNum=0;
int curDen=0;
boolean isNeg = false;
char ch = expression.charAt(i);
if(ch == '+' || ch == '-'){
if(ch=='-'){
isNeg = true;
}
i++;
}
//form the num
int start=i;
while(Character.isDigit(expression.charAt(i))){
i++;
}
curNum = Integer.parseInt(expression.substring(start,i));
if(isNeg) curNum*=-1;
i++; //skip /
//form the den
start=i;
while(i<n && Character.isDigit(expression.charAt(i))){
i++;
}
curDen = Integer.parseInt(expression.substring(start,i));
num = num * curDen + curNum * den;
den *= curDen;
}
int gcd = Math.abs(getGCD(num,den));
num/=gcd;
den/=gcd;
return num + "/" + den;
}
public int getGCD(int a, int b){
if(a==0) return b;
return getGCD(b%a,a);
}
}