exercism/go/trinary/trinary.go

34 lines
740 B
Go
Raw Normal View History

2016-09-06 16:51:22 +00:00
package trinary
import (
"errors"
2016-09-08 11:39:08 +00:00
"math/big"
2016-09-06 16:51:22 +00:00
)
// ParseTrinary takes a trinary string and returns the
// decimal value
func ParseTrinary(in string) (int64, error) {
2016-09-08 11:39:08 +00:00
return convertNumStringBase(in, int64(3))
}
2016-09-06 16:51:22 +00:00
2016-09-08 11:39:08 +00:00
// convertNumStringBase takes a numeric string and the base of that string
// and returns an int64 of the decimal representation
func convertNumStringBase(in string, oldBase int64) (int64, error) {
base := big.NewInt(oldBase)
var sum big.Int
2016-09-06 16:51:22 +00:00
for i := range in {
2016-09-08 11:39:08 +00:00
x := big.NewInt(int64(in[i] - '0'))
pow := big.NewInt(int64(len(in) - i - 1))
var n big.Int
n.Exp(base, pow, nil)
n.Mul(x, &n)
sum.Add(&sum, &n)
if sum.Int64() < 0 {
return 0, errors.New("Integer Overflow")
2016-09-06 16:51:22 +00:00
}
}
2016-09-08 11:39:08 +00:00
return sum.Int64(), nil
2016-09-06 16:51:22 +00:00
}