Guest User

Untitled

a guest
Jun 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. /**
  2. 640. Solve the Equation
  3.  
  4. 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.
  5.  
  6. If there is no solution for the equation, return "No solution".
  7.  
  8. If there are infinite solutions for the equation, return "Infinite solutions".
  9.  
  10. If there is exactly one solution for the equation, we ensure that the value of x is an integer.
  11.  
  12. Example 1:
  13. Input: "x+5-3+x=6+x-2"
  14. Output: "x=2"
  15. Example 2:
  16. Input: "x=x"
  17. Output: "Infinite solutions"
  18. Example 3:
  19. Input: "2x=x"
  20. Output: "x=0"
  21. Example 4:
  22. Input: "2x+3x-6x=x+2"
  23. Output: "x=-1"
  24. Example 5:
  25. Input: "x=x+2"
  26. Output: "No solution"
  27.  
  28.  
  29. testcase:
  30. "x+5-3+x=6+x-2"
  31. "-x=-1"
  32. "x=x"
  33. "2x=x"
  34. "2x+3x-6x=x+2"
  35. "x=x+2"
  36. "2-x+x+3x=2x-x+x+3"
  37. **/
  38.  
  39. import (
  40. "strings"
  41. "strconv"
  42. )
  43. func solveEquation(equation string) string {
  44. var res [][]int = [][]int{{0,0},{0,0}}
  45. for i,s := range strings.Split(equation, "=") {
  46. res[i][0], res[i][1] = coefficient(s)
  47. }
  48.  
  49. l := res[0][0] - res[1][0]
  50. r := res[0][1] - res[1][1]
  51. r *= -1
  52.  
  53. if l ==0 && r == 0 {
  54. return "Infinite solutions"
  55. } else if l == 0 {
  56. return "No solution"
  57. } else if r == 0 {
  58. return "x=0"
  59. } else {
  60. return "x="+strconv.Itoa(r/l)
  61. }
  62. }
  63.  
  64. func coefficient(s string) (int, int) {
  65. co, val := 0, 0
  66. out := ""
  67. for _, c := range s {
  68. if strings.ContainsAny(string(c), "+-") {
  69. if len(out)>0 {
  70. _co, _val := conv(out)
  71. co += _co
  72. val += _val
  73. out = ""
  74. }
  75. if c == '+' {
  76. continue
  77. }
  78. }
  79. out += string(c)
  80. }
  81. _co, _val := conv(out)
  82. co += _co
  83. val += _val
  84. return co, val
  85. }
  86.  
  87. func conv(s string) (int,int) {
  88. co, val := 0, 0
  89.  
  90. if strings.ContainsRune(s, 'x') {
  91. if s == "x" {
  92. co = 1
  93. } else if s == "-x" {
  94. co = -1
  95. } else {
  96. fmt.Println(s[:len(s)-1])
  97. co,_ = strconv.Atoi(s[:len(s)-1])
  98. }
  99. } else {
  100. val,_ = strconv.Atoi(s)
  101. }
  102. return co, val
  103. }
Add Comment
Please, Sign In to add comment