BinaryEquivalent [二进制转化]
# 介绍
利用递归将十进制数字转化为二进制。可以推广到任意进制的互相转换。
# 实现
# JavaScript
/*
* Problem Statement: Given a positive number `num`, find it's binary equivalent using recursion
*
* What is Binary Equivalent?
* - In binary number system, a number is represented in terms of 0s and 1s,
* for example:
* - Binary Of 2 = 10
* - Binary of 3 = 11
* - Binary of 4 = 100
*
* Reference on how to find Binary Equivalent
* - https://byjus.com/maths/decimal-to-binary/
*
*/
export const binaryEquivalent = (num) => {
if (num === 0 || num === 1) {
return String(num)
}
return binaryEquivalent(Math.floor(num / 2)) + String(num % 2)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
编辑 (opens new window)
上次更新: 2022/06/20, 20:15:04