640.solve-the-equation.go 748 B

123456789101112131415161718192021222324252627282930313233343536
  1. func solveEquation(equation string) string {
  2. part := strings.Split(equation, "=")
  3. x1, a1 := parse(part[0])
  4. x2, a2 := parse(part[1])
  5. if x1 == x2 && a1 == a2 {
  6. return "Infinite solutions"
  7. } else if x1 != x2 {
  8. return fmt.Sprintf("x=%d", (a2-a1)/(x1-x2))
  9. } else {
  10. return "No solution"
  11. }
  12. }
  13. func parse(eq string) (x int, a int) {
  14. pre, n := 0, len(eq)
  15. for i := range eq {
  16. if eq[i] == 'x' || i == n-1 || eq[i+1] == '-' || eq[i+1] == '+' {
  17. if eq[i] == 'x' {
  18. switch eq[pre:i] {
  19. case "", "+": // Handle special case
  20. x += 1
  21. case "-":
  22. x -= 1
  23. default:
  24. num, _ := strconv.Atoi(eq[pre:i])
  25. x += num
  26. }
  27. } else {
  28. num, _ := strconv.Atoi(eq[pre : i+1])
  29. a += num
  30. }
  31. pre = i + 1
  32. }
  33. }
  34. return
  35. }