Skip to content

Commit

Permalink
fix: fix the DecimalNumberToBinary function
Browse files Browse the repository at this point in the history
  • Loading branch information
WGrape committed May 30, 2023
1 parent aa57e5c commit ac593f8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
20 changes: 16 additions & 4 deletions binary/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,26 @@
// Package binary provides some operations of binary number and decimal number.
package binary

import "fmt"

// DecimalNumberToBinary Return a binary array.
func DecimalNumberToBinary(num int) []int {
var binary []int
func DecimalNumberToBinary(num int) ([]int, []string, string) {
var (
binary []int
binaryString []string
str string
)

for num != 0 {
binary = append(binary, num%2)
var (
bit = num % 2
bitStr = fmt.Sprintf("%d", bit)
)
binary = append([]int{bit}, binary...)
binaryString = append([]string{bitStr}, binaryString...)
str = bitStr + str
num = num / 2
}

return binary
return binary, binaryString, str
}
4 changes: 2 additions & 2 deletions binary/binary_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package binary

import (
"github.com/WGrape/golib/array"
"reflect"
"testing"
)

// TestDecimalNumberToBinary Test the function DecimalNumberToBinary
func TestDecimalNumberToBinary(t *testing.T) {
if !reflect.DeepEqual(array.Reverse(DecimalNumberToBinary(4)), []int{1, 0, 0}) {
var intArr, strArr, str = DecimalNumberToBinary(4)
if !reflect.DeepEqual(intArr, []int{1, 0, 0}) || !reflect.DeepEqual(strArr, []string{"1", "0", "0"}) || str != "100" {
t.Fail()
return
}
Expand Down

0 comments on commit ac593f8

Please sign in to comment.