exercism/go/binary/binary.go

23 lines
422 B
Go

package binary
import "fmt"
// ParseBinary takes a binary string and returns the
// integer representation of it.
func ParseBinary(bin string) (int, error) {
var ret int
currSpot := 1
for len(bin) > 0 {
v := bin[len(bin)-1]
if v != '0' && v != '1' {
return 0, fmt.Errorf("Invalid String")
}
if v == '1' {
ret = ret + currSpot
}
currSpot = currSpot * 2
bin = bin[:len(bin)-1]
}
return ret, nil
}