Untitled
raw download clone
TEXT
views 12
,
size 2150 b
bool check(string s) {
    for (int i = 0; i < s.length(); i++)
		if (s[i] == '{') return true;
	return false;
}

int strtonum(string &s) {
    int sum = 0, m = 1;
    for (int i = s.length() - 1; i >= 0; i--) {
        sum = sum + (s[i] - 48)*m;
        m = m*10;
    }
    return sum;
}

string getString(string s) {
    string str;
	int end = -1;
	for (int i = 0; i < s.length(); i++) {
		if (s[i] == '{') end = i;
	}
	
	for (int i = 0; i < end; i++) {
	    str += s[i];
	}
	return str;
}

string getPolynomial(string s) {
    string polynomial;
    int start = -1;
	int end = -1;
	for (int i = 0; i < s.length(); i++) {
		if (s[i] == '{') start = i;
		if (s[i] == '}') end = i;
	}	
	
	for (int i = start + 1; i < end; i++) {
	    polynomial += s[i];
	}
	return polynomial;
}

int getPosOperator(string &s) {
    for (int i = 0; i < s.length(); i++) {
        if ((s[i] == '+')) return i;
        if ((s[i] == '-')) return i;
        if ((s[i] == '*')) return i;
    }
}

int checkOperator(string s) {
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '+') return 1;
        if (s[i] == '-') return 2;
        if (s[i] == '*') return 3;
    }
}

string tinhXau(string str) {
    string s = getString(str);
    if (check(str) == false) return str;
    else {
        string polynomial = getPolynomial(str);
        int pos = getPosOperator(polynomial);
        string left, right;
        for (int i = 0; i < pos; i++) left += polynomial[i];
        for (int i = pos + 1; i < polynomial.length(); i++) right += polynomial[i];
        if (checkOperator(polynomial) == 1) {
            int plus = strtonum(left) + strtonum(right);
            s = s + to_string(plus) + ".";
        }
        
        if (checkOperator(polynomial) == 2) {
            int subtract = strtonum(left) - strtonum(right);
            s = s + to_string(subtract) + ".";
        }
        
        if (checkOperator(polynomial) == 3) {
            int product = strtonum(left) * strtonum(right);
            s = s + to_string(product) + ".";
        }
        return s;
    }
}
close fullscreen
Login or Register to edit or fork this paste. It's free.