Java String.split()


  • 0
    H
        public String fractionAddition(String expression) {
            if(expression == null || expression.length() == 0){ return "";}
            
            String[] inputs = expression.split("(?=[+-])");        
            int num;	int den;        
            char[] first = inputs[0].toCharArray();
            if(first[0] != '-'){
            	String[] parts = inputs[0].split("/");
            	num = Integer.parseInt(parts[0]);
            	den = Integer.parseInt(parts[1]);
            }else{
            	String[] parts = inputs[0].substring(1).split("/");
            	num = -Integer.parseInt(parts[0]);
            	den = Integer.parseInt(parts[1]);        	
            }
            
            
            for(int i=1;i<inputs.length;i++){
            	String[] parts = inputs[i].substring(1).split("/");
            	int cnum = Integer.parseInt(parts[0]);
            	int cden = Integer.parseInt(parts[1]);  
            	if(inputs[i].charAt(0) == '+'){
            		//Addition
            		num = num*cden+den*cnum;
            		den = den*cden;
            	}else{
            		//Minus
            		num = num*cden-den*cnum;
            		den = den*cden;        		
            	}
            }        
        	if(den < 0){
        		den *=-1;
        		num *=-1;
        	}        
            
            int offset = 0;	boolean pos = true;
            if(num <0){
            	pos = false;	num*=-1;
            }
            if(num > den){
            	offset = num / den;
            	num = num % den;
            }else if(num == den){
                if(pos){
                	return ""+Integer.toString(1)+"/"+Integer.toString(1);
                }else{
                	return "-"+Integer.toString(1)+"/"+Integer.toString(1);
                }        	
            }        
        	int gcd = GCD(den,num);
        	num = num / gcd;		den = den /gcd;
        	num += offset*den;
            
            if(pos){
            	return ""+Integer.toString(num)+"/"+Integer.toString(den);
            }else{
            	return "-"+Integer.toString(num)+"/"+Integer.toString(den);
            }
        }
        
        public int GCD(int a, int b) {
        	   if (b==0) return a;
        	   return GCD(b,a%b);
        }
    

Log in to reply
 

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