Dada una ecuación lineal, la tarea es encontrar el valor de la variable utilizada. La ecuación contiene solo la operación ‘+’, ‘-‘, la variable y su coeficiente.
- Si no hay solución para la ecuación, devuelve «Sin solución».
- Si hay soluciones infinitas para la ecuación, devuelve «Soluciones infinitas».
- Si hay exactamente una solución para la ecuación, asegúrese de que el valor de x sea un número entero.
Ejemplos:
Input : "x + 5 - 3 + x = 6 + x - 2" Output : "x = 2" Input : "x = x" Output : "Infinite solutions" Input: "2x = x" Output: "x = 0" Input: "x = x + 2" Output: "No solution"
Enfoque: La idea es utilizar dos punteros para actualizar dos parámetros: el coeficiente de la variable utilizada y la suma total. En el lado izquierdo y derecho de ‘=’, use signos opuestos para cada número que está a cargo de una variable de signo, que cambiará una vez que se vea ‘=’.
Ahora, en el caso de una solución única, la relación entre el total efectivo y el coeficiente da el resultado requerido. En el caso de soluciones infinitas, tanto el total efectivo como el coeficiente resultan ser cero, por ejemplo, x + 1 = x + 1. En caso de que no haya solución, el coeficiente de x resulta ser cero, pero el total efectivo es distinto de cero. .
C++
// CPP program to solve the given equation #include <bits/stdc++.h> using namespace std; // Function to solve the given equation string solveEquation(string equation) { int n = equation.size(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); i = j; } // For cases such as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * stoi(equation.substr(i, j - i)); i = j + 1; } // Flip sign once '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); sign = -1; i = j + 1; } } // There may be a number left in the end if (i < n) total += sign * stoi(equation.substr(i)); // For infinite solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total) return "No solution"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side int ans = -total / coeff; return "x=" + to_string(ans); } // Driver code int main() { string equation = "x+5-3+x=6+x-2"; cout << solveEquation(equation); return 0; }
Java
// Java program to solve // the given equation import java.io.*; class GFG { // Function to solve // the given equation static String solveEquation(String equation) { int n = equation.length(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation.charAt(j) == '+' || equation.charAt(j) == '-') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); i = j; } // For cases such // as: x, -x, +x else if (equation.charAt(j) == 'x') { if ((i == j) || equation.charAt(j - 1) == '+') coeff += sign; else if (equation.charAt(j - 1) == '-') coeff -= sign; else coeff += sign * Integer.parseInt( equation.substring(i, j)); i = j + 1; } // Flip sign once // '=' is seen else if (equation.charAt(j) == '=') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total = total + sign * Integer.parseInt( equation.substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total != 0) return "No solution"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return (Integer.toString(ans)); } // Driver code public static void main(String args[]) { String equation = new String("x+5-3+x=6+x-2"); System.out.print("x = " + solveEquation(equation)); } } // This code is contributed by // Manish Shaw(manishshaw1)
Python3
# Python program to solve # the given equation # def to solve # the given equation def solveEquation(equation) : n = len(equation) sign = 1 coeff = 0 total = 0 i = 0 # Traverse the equation for j in range(0, n) : if (equation[j] == '+' or equation[j] == '-') : if (j > i) : total = (total + sign * int(equation[i: j])) i = j # For cases such # as: x, -x, +x elif (equation[j] == 'x') : if ((i == j) or equation[j - 1] == '+') : coeff += sign elif (equation[j - 1] == '-') : coeff = coeff - sign else : coeff = (coeff + sign * int(equation[i: j])) i = j + 1 # Flip sign once # '=' is seen elif (equation[j] == '=') : if (j > i) : total = (total + sign * int(equation[i: j])) sign = -1 i = j + 1 # There may be a number # left in the end if (i < n) : total = (total + sign * int(equation[i: len(equation)])) # For infinite solutions if (coeff == 0 and total == 0) : return "Infinite solutions" # For no solution if (coeff == 0 and total) : return "No solution" # x = total sum / coeff of x # '-' sign indicates moving # numeric value to right hand side ans = -total / coeff return int(ans) # Driver code equation = "x+5-3+x=6+x-2" print ("x = {}" . format(solveEquation(equation))) # This code is contributed by # Manish Shaw(manishshaw1)
C#
// C# program to solve // the given equation using System; class GFG { // Function to solve // the given equation static string solveEquation(string equation) { int n = equation.Length, sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); i = j; } // For cases such // as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * Int32.Parse( equation.Substring(i, j - i)); i = j + 1; } // Flip sign once // '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total += sign * Int32.Parse( equation.Substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total != 0) return "No solution"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return "x = " + ans.ToString(); } // Driver code static void Main() { string equation = "x+5-3+x=6+x-2"; Console.Write(solveEquation(equation)); } } // This code is contributed by // Manish Shaw(manishshaw1)
PHP
<?php // PHP program to solve // the given equation // Function to solve // the given equation function solveEquation($equation) { $n = strlen($equation); $sign = 1; $coeff = 0; $total = 0; $i = 0; // Traverse the equation for ($j = 0; $j < $n; $j++) { if ($equation[$j] == '+' || $equation[$j] == '-') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $i = $j; } // For cases such // as: x, -x, +x else if ($equation[$j] == 'x') { if (($i == $j) || $equation[$j - 1] == '+') $coeff += $sign; else if ($equation[$j - 1] == '-') $coeff -= $sign; else $coeff += $sign * intval(substr($equation, $i, $j - $i)); $i = $j + 1; } // Flip sign once // '=' is seen else if ($equation[$j] == '=') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $sign = -1; $i = $j + 1; } } // There may be a number // left in the end if ($i < $n) $total += $sign * intval(substr($equation, $i)); // For infinite solutions if ($coeff == 0 && $total == 0) return "Infinite solutions"; // For no solution if ($coeff == 0 && $total) return "No solution"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side $ans = -$total / $coeff; return "x = " . $ans; } // Driver code $equation = "x+5-3+x=6+x-2"; echo (solveEquation($equation)); // This code is contributed by // Manish Shaw(manishshaw1) ?>
x = 2
Complejidad temporal: O(n), donde n es la longitud de la string de ecuaciones.
Espacio Auxiliar : O(1)