Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- 640. Solve the Equation
- Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
- If there is no solution for the equation, return "No solution".
- If there are infinite solutions for the equation, return "Infinite solutions".
- If there is exactly one solution for the equation, we ensure that the value of x is an integer.
- Example 1:
- Input: "x+5-3+x=6+x-2"
- Output: "x=2"
- Example 2:
- Input: "x=x"
- Output: "Infinite solutions"
- Example 3:
- Input: "2x=x"
- Output: "x=0"
- Example 4:
- Input: "2x+3x-6x=x+2"
- Output: "x=-1"
- Example 5:
- Input: "x=x+2"
- Output: "No solution"
- testcase:
- "x+5-3+x=6+x-2"
- "-x=-1"
- "x=x"
- "2x=x"
- "2x+3x-6x=x+2"
- "x=x+2"
- "2-x+x+3x=2x-x+x+3"
- **/
- import (
- "strings"
- "strconv"
- )
- func solveEquation(equation string) string {
- var res [][]int = [][]int{{0,0},{0,0}}
- for i,s := range strings.Split(equation, "=") {
- res[i][0], res[i][1] = coefficient(s)
- }
- l := res[0][0] - res[1][0]
- r := res[0][1] - res[1][1]
- r *= -1
- if l ==0 && r == 0 {
- return "Infinite solutions"
- } else if l == 0 {
- return "No solution"
- } else if r == 0 {
- return "x=0"
- } else {
- return "x="+strconv.Itoa(r/l)
- }
- }
- func coefficient(s string) (int, int) {
- co, val := 0, 0
- out := ""
- for _, c := range s {
- if strings.ContainsAny(string(c), "+-") {
- if len(out)>0 {
- _co, _val := conv(out)
- co += _co
- val += _val
- out = ""
- }
- if c == '+' {
- continue
- }
- }
- out += string(c)
- }
- _co, _val := conv(out)
- co += _co
- val += _val
- return co, val
- }
- func conv(s string) (int,int) {
- co, val := 0, 0
- if strings.ContainsRune(s, 'x') {
- if s == "x" {
- co = 1
- } else if s == "-x" {
- co = -1
- } else {
- fmt.Println(s[:len(s)-1])
- co,_ = strconv.Atoi(s[:len(s)-1])
- }
- } else {
- val,_ = strconv.Atoi(s)
- }
- return co, val
- }
Add Comment
Please, Sign In to add comment