go: add «592. Fraction Addition and Subtraction»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-23 23:42:16 +02:00
parent a31b0d7cdf
commit b4b3c16c58
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,45 @@
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)
}