592.fraction-addition-and-subtraction.go 805 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. type pair struct {
  2. _1 int
  3. _2 int
  4. }
  5. func (p1 *pair) add(p2 pair) {
  6. if p1._1 == 0 {
  7. *p1 = p2
  8. } else {
  9. p1._1 = p1._1*p2._2 + p2._1*p1._2
  10. p1._2 *= p2._2
  11. }
  12. }
  13. func fractionAddition(expression string) string {
  14. beg, end, n := 0, 1, len(expression)
  15. var sum pair
  16. for end < n {
  17. for end = beg + 1; end < n && expression[end] != '+' && expression[end] != '-'; end++ {
  18. }
  19. p := str2frac(expression[beg:end])
  20. sum.add(p)
  21. beg = end
  22. }
  23. i := gcd(abs(sum._1), sum._2)
  24. return fmt.Sprintf("%d/%d", sum._1/i, sum._2/i)
  25. }
  26. func gcd(a, b int) int {
  27. if b == 0 {
  28. return a
  29. }
  30. return gcd(b, a%b)
  31. }
  32. func str2frac(s string) (p pair) {
  33. strs := strings.Split(s, "/")
  34. p._1, _ = strconv.Atoi(strs[0])
  35. p._2, _ = strconv.Atoi(strs[1])
  36. return
  37. }
  38. func abs(x int) int {
  39. if x < 0 {
  40. return -x
  41. }
  42. return x
  43. }