This commit is contained in:
2016-09-08 06:39:08 -05:00
parent 1572f99a57
commit 148fad68a9
8 changed files with 232 additions and 23 deletions

View File

@@ -2,30 +2,32 @@ package trinary
import (
"errors"
"fmt"
"math"
"math/big"
)
// ParseTrinary takes a trinary string and returns the
// decimal value
func ParseTrinary(in string) (int64, error) {
fmt.Println("=== New Parse (" + in + ") ===")
var ret int
place := len(in)
for i := range in {
fmt.Print("Finding ", (place - i), " place value ", string(in[i]))
switch in[i] {
case '0':
case '1':
ret = ret + ((place - i) * 3)
case '2':
ret = ret + ((place - i) * int(math.Pow(3, 2)))
default:
return 0, errors.New("Invalid String")
}
fmt.Println("==", ret)
place--
}
return int64(ret), nil
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
}