Java, Little Library Call Solution (beats 88.84%)


  • 0
    K

    class Solution {

    public String solveEquation(String str) {
        int len = str.length();
        int num = 0;
        int x = 0;
        int index = 0;
        
        int co;
        char ch;
        boolean positive = true;
        boolean hasCo = false;
        
        while (index < len) {
            co = 0;
            ch = str.charAt(index++);
            hasCo = ch >= '0' && ch <= '9';
            
            while (ch <= '9' && ch >= '0') {
                co *= 10;
                co += ch - '0';
                
                if (index < len) {
                    ch = str.charAt(index++);
                } else {
                    ch = 0;
                }
            }
            
            if (!positive) {
                co = -co;
            }
            
            if (ch == 'x') {
                x += (!hasCo) ? (positive ? 1: -1) : co;    
            } else {
                num += co;
            }
            
            if (ch == '+') {
                positive = true;
            } else if (ch == '-') {
                positive = false;
            } else if (ch == '=') {
                num = -num;
                x = -x;
                positive = true;
            }
        }
        
        if (x == 0) {
            return (num == 0) ? "Infinite solutions" : "No solution";
        }
        return "x=" + (-num / x);
    }
    

    }


Log in to reply
 

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