LeetCode/go/fraction-addition-and-subtraction.go

46 lines
753 B
Go
Raw Normal View History

package main
import (
"fmt"
"regexp"
"strconv"
)
func fractionAddition(expression string) string {
abs := func(x int) int {
return max(-x, x)
}
gcd := func(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
NUM_REGEX, _ := regexp.Compile("[+-]?[0-9]+")
num, denom := 0, 1
nums := NUM_REGEX.FindAllString(expression, -1)
for i := 0; i < len(nums); i += 2 {
next_num, ok := strconv.Atoi(nums[i])
if ok != nil {
panic("failed to parse numerator")
}
next_denom, ok := strconv.Atoi(nums[i+1])
if ok != nil {
panic("failed to parse denominator")
}
num = num*next_denom + next_num*denom
denom *= next_denom
}
d := abs(gcd(num, denom))
num /= d
denom /= d
return fmt.Sprintf("%d/%d", num, denom)
}