go: add «592. Fraction Addition and Subtraction»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
a31b0d7cdf
commit
b4b3c16c58
1 changed files with 45 additions and 0 deletions
45
go/fraction-addition-and-subtraction.go
Normal file
45
go/fraction-addition-and-subtraction.go
Normal 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)
|
||||
}
|
Loading…
Reference in a new issue