exercism/go/trinary/trinary.go
2016-09-08 06:39:08 -05:00

34 lines
740 B
Go

package trinary
import (
"errors"
"math/big"
)
// ParseTrinary takes a trinary string and returns the
// decimal value
func ParseTrinary(in string) (int64, error) {
return convertNumStringBase(in, int64(3))
}
// 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
for i := range in {
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")
}
}
return sum.Int64(), nil
}