forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decimaltobinary.go
45 lines (40 loc) · 1.07 KB
/
decimaltobinary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
Author: Motasim
GitHub: https://github.com/motasimmakki
Date: 14-Oct-2021
*/
// This algorithm will convert any Decimal (+ve integer) number to Binary number.
// https://en.wikipedia.org/wiki/Binary_number
// Function receives a integer as a Decimal number and returns the Binary number.
// Supported integer value range is 0 to 2^(31 -1).
package conversion
// Importing necessary package.
import (
"errors"
"strconv"
)
// Reverse() function that will take string,
// and returns the reverse of that string.
func Reverse(str string) string {
rStr := []rune(str)
for i, j := 0, len(rStr)-1; i < len(rStr)/2; i, j = i+1, j-1 {
rStr[i], rStr[j] = rStr[j], rStr[i]
}
return string(rStr)
}
// DecimalToBinary() function that will take Decimal number as int,
// and return it's Binary equivalent as string.
func DecimalToBinary(num int) (string, error) {
if num < 0 {
return "", errors.New("integer must have +ve value")
}
if num == 0 {
return "0", nil
}
var result string = ""
for num > 0 {
result += strconv.Itoa(num & 1)
num >>= 1
}
return Reverse(result), nil
}