Skip to content

Commit

Permalink
all your base improved build
Browse files Browse the repository at this point in the history
  • Loading branch information
davidjayatillake committed Oct 12, 2021
1 parent ac5cc09 commit 921f0d6
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions all-your-base/all_your_base.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package allyourbase

import (
"errors"
"math"
)

func ConvertToBase(inputBase int, inputDigits []int, outputBase int) ([]int, error) {
Expand All @@ -14,25 +13,19 @@ func ConvertToBase(inputBase int, inputDigits []int, outputBase int) ([]int, err
} else if len(inputDigits) == 0 {
return []int{0}, nil
}

decimal := 0
for i, digit := range inputDigits {
for _, digit := range inputDigits {
if digit >= inputBase || digit < 0 {
return []int{}, errors.New("all digits must satisfy 0 <= d < input base")
}
decimal += digit * int(math.Pow(float64(inputBase), float64(len(inputDigits)-1-i)))
decimal = inputBase*decimal + digit
}
if decimal == 0 {
return []int{0}, nil
}
dec_exp := math.Log(float64(decimal)) / math.Log(float64(outputBase))
dec_exp_int := int(dec_exp)
output := make([]int, dec_exp_int+1)
for i := 0; i < dec_exp_int+1; i++ {
base_p := int(math.Pow(float64(outputBase), float64(dec_exp_int-i)))
digit := decimal / base_p
output[i] = digit
decimal -= base_p * digit
output := []int{}
for ; decimal > 0; decimal /= outputBase {
output = append([]int{decimal % outputBase}, output...)
}
return output, nil
}

0 comments on commit 921f0d6

Please sign in to comment.