-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_system.js
More file actions
65 lines (55 loc) · 1.67 KB
/
Copy pathbinary_system.js
File metadata and controls
65 lines (55 loc) · 1.67 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"use strict";
function toBinary(num) {
function calculationProcess(number) {
let remainder;
let result = [];
for(let i = 0; number > 0; i++) {
remainder = (number / 2) - Math.trunc(number / 2);
number = Math.floor(number / 2);
if(remainder > 0) {
result.push(1);
} else if(remainder === 0){
result.push(0);
}
}
return result;
}
if(num === 0) {
return '0';
} else if(Math.sign(num) === -1) {
num = Math.abs(num);
const res = calculationProcess(num);
res.push('-');
return res.reverse().join('');
} else {
return calculationProcess(num).reverse().join('');
}
}
function toDecimal(num) {
if(num === 0) {
return 0;
}
const splitNum = num.split('').reverse();
if(splitNum[splitNum.length - 1] !== '-') {
let result = 0;
for(let i = 0; i < splitNum.length; i++) {
if (+splitNum[i] > 0) {
result = result + Math.pow(2, i);
}
}
return result;
} else if(splitNum[splitNum.length - 1] === '-') {
let result = 0;
for(let i = 0; i < splitNum.length; i++) {
if (+splitNum[i] > 0) {
result = result + Math.pow(2, i);
}
}
return (result * -1);
}
}
console.log(toDecimal(toBinary(136)));
console.log(toDecimal(toBinary(-654132654)));
console.log(toDecimal(toBinary(136654)));
console.log(toDecimal(toBinary(-16)));
console.log(toDecimal(toBinary(0)));