Java Code: new Class Fraction


  • 0
    K
    public class Solution {    
        class Fraction
        {
            private int up,down;
            private int gcd(int a,int b)
            {
                if (a>b) return gcd(b,a);
                if (a==0) return b;
                return gcd(b%a,a);
            }
            Fraction (int a, int b) 
            { 
                down=Math.abs(b);
                up=a*(down/b);
                int c=gcd(Math.abs(a),down);
                up/=c; 
                down/=c;
            }
            Fraction (String s) 
            { 
                this(Integer.parseInt(s.split("/")[0]),Integer.parseInt(s.split("/")[1]));
            }
            public String toString()
            {
                return String.valueOf(up)+"/"+String.valueOf(down);
            }
            public Fraction plus(Fraction x)
            {
                return new Fraction(x.up*down+x.down*up,x.down*down);
            }
        }
        public String fractionAddition(String expression) {
            Fraction ans=new Fraction(0,1);
            String[] fracs=expression.split("(?=[-+])");
            for (String s:fracs) ans=ans.plus(new Fraction(s));
            return ans.toString();
        }
    }
    

Log in to reply
 

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