A directory
What’s the difference between a free front end and a salted fish
directory |
---|
A directory |
The preface |
Three string sum/difference |
Four decimal to binary |
Five binary to decimal |
Six summarize |
The preface
In the course of your career, you’ll come across a question that will embarrass you:
- How to convert from decimal to binary?
- How to convert binary to decimal?
If you are quite familiar with the JS API, then you are familiar with it:
- Decimal to binary:
num.toString(2)
- Binary to decimal:
parseInt(num, 2)
Because there are tools for both of these problems in JavaScript, you can simply apply them to the numbers that need to be converted.
However, let’s take it a step further:
- If you need to improve performance
- If you want to convert large numbers
Why do you say that? Let’s take toString() :
- MDN – toString()
Explanation: The toString() method returns the string representation of the specified Number object. Syntax: numobj.tostring ([radix]) parameter: radix specifies the radix (from 2 to 36) to be used for numeric toString conversion. If the RADIX parameter is not specified, the default value is 10. Description: If the cardinality is not specified, 10 is used. If the object is negative, the minus sign is retained. This is true even when the radix is 2: the returned string contains a negative (-) prefix and a binary representation of a positive number, not the binary complement of the number.Copy the code
Very good, see here we can clearly know, Number. The prototype. The toString () to a negative Number is powerless.
Also, in the LeetCode title “1018- Binary prefix divisible by 5”, Jsliang found that large numbers (exceeding JavaScript’s number.max_safe_INTEGER limit) could not be accurately converted to binary.
In this case, you want to know how to convert binary out of the units digit of decimal, because the units digit is divisible by 5 only if it is 5 or 0.
Num. ToString (2) or parseInt(num, 2).
No, change the keyword, directly search binary to decimal, find a few good non-code explanation:
- www.cnblogs.com/web-record/…
- www.cnblogs.com/xkfz007/art…
So let’s start converting to programming languages so that we can use them directly in the future!
Three string sum/difference
In the course of writing this article, jsliang found that the sum of strings can be made into a common function, and then directly hit the inside of the two problems:
- 67. Binary summation
- 415. String addition
String summation (base 2 and base 10 supported)
/** * @name stringAddtion * @description String summation * @param {string} a plus one * @param {string} b plus two * @param {any} base Base (default decimal) * @return Returns the calculation result */
const stringAddtion = (a = ' ', b = ' ', base = 10) = > {
/ / the result
let result = ' ';
// carry flag
let carry = 0;
// Set the length of a and b to facilitate reverse traversal
let aIndex = a.length - 1, bIndex = b.length - 1;
while (aIndex >= 0 || bIndex >= 0) { // A and B still have bits to add
// aIndex bIndex may be negative and needs to be converted to 0
sum = (+a[aIndex] || 0) + (+b[bIndex] || 0) + carry;
// Whether carry is required
carry = sum >= base ? 1 : 0;
// Calculate the final result
result = sum % base + result;
// Move to a higher position
aIndex--;
bIndex--;
}
// If there is a carry after the calculation, then the front + 1
if (carry) {
result = '1' + result;
}
// Return the final result
return result;
};
Copy the code
Similarly, I don’t know if there is a problem for the difference of string, because jsliang brush too many questions, forget whether there is a difference, but because it will be used below, so here extract it and put it:
String difference (support base 2 and base 10)
/** * @name stringDifference * @description String difference * @param {string} a subtraction one * @param {string} b subtraction two * @param {any} base Base (default decimal) * @return Returns the calculation result */
const stringDifference = (a = ' ', b = ' ', base = 10) = > {
/ / the result
let result = ' ';
// The borrowing flag
let carry = 0;
// Set the length of a and b to facilitate reverse traversal
let aIndex = a.length - 1, bIndex = b.length - 1;
while (aIndex >= 0 || bIndex >= 0) { // We can subtract a and b
// Determine whether you need to borrow
let reduce = 0;
if ((+a[aIndex] || 0) < (+b[bIndex] || 0)) {
reduce = (+a[aIndex] || 0) + base - (+b[bIndex]);
carry = 1;
} else {
reduce = (+a[aIndex] || 0) - (+b[bIndex] || 0) - carry;
carry = 0;
}
// Calculate the final result
result = reduce % base + result;
// Move to a higher position
aIndex--;
bIndex--;
}
// Return the final result
return result;
};
Copy the code
Four decimal to binary
Attention! The decimal to binary conversion here includes:
- Positive integer [0, n]
- Negative integer [n, 0]
- The decimal (0, 1)
- The decimal (1, n)
It doesn’t include negative decimals. It doesn’t include negative decimals. It doesn’t include negative decimals
/** * @name stringAddtion * @description String summation * @param {string} a plus one * @param {string} b plus two * @param {any} base Base (default decimal) * @return Returns the calculation result */
const stringAddtion = (a = ' ', b = ' ', base = 10) = > {
/ / the result
let result = ' ';
// carry flag
let carry = 0;
// Set the length of a and b to facilitate reverse traversal
let aIndex = a.length - 1, bIndex = b.length - 1;
while (aIndex >= 0 || bIndex >= 0) { // A and B still have bits to add
// aIndex bIndex may be negative and needs to be converted to 0
let sum = (+a[aIndex] || 0) + (+b[bIndex] || 0) + carry;
// Whether carry is required
carry = sum >= base ? 1 : 0;
// Calculate the final result
result = sum % base + result;
// Move to a higher position
aIndex--;
bIndex--;
}
// If there is a carry after the calculation, then the front + 1
if (carry) {
result = '1' + result;
}
// Return the final result
return result;
};
* EQU - equal to: equal * NEQ - not equal * LSS - less than: less than * LEQ - less than or equal to: Equal or less than * GTR - Greater than * GEQ - Equal or greater than */
/** * @name integerLEQZero * @description Converts integers greater than or equal to 0 to binary * @param {number} number * @return Binary string */
const integerGEQZero = (number) = > {
let result = ' ';
while (number >= 1) {
result = number % 2 + result;
number = Math.floor(number / 2);
}
return result;
};
/** * @name integerLSSZero * @description Converts integers less than 0 to binary * @param {number} number * @return Binary string */
const integerLSSZero = (number) = > {
let result = ' ';
/ / positive
number = -number;
// select binary and invert
while (number >= 1) {
if (number % 2= = =1) {
result = '0' + result;
} else {
result = '1' + result;
}
number = Math.floor(number / 2);
}
/ / completion
if (result.length < 8) {
result = '1'.repeat(8 - result.length) + result;
}
/ / plus one
result = stringAddtion(result, '1'.2);
return result;
};
/** * @name floorGTROne * @description > 1 decimal to binary * @param {number} number * @return binary string */
const floorGTROne = (number) = > {
let result = ' ';
const integer = Math.floor(number);
const decimal = number - integer;
result += integerGEQZero(integer) + '. ' + floorBetweenZeroOne(decimal).split('. ') [1];
return result;
};
/** * @name floorBetweenZeroOne * @description > 0 > 1 decimal to binary * @param {number} number * @return binary string */
const floorBetweenZeroOne = (number) = > {
let result = ' ';
while( number ! =0&& number ! =1 // The value is up to 0 or 1
&& result.length < 32 // Or the desired length
) {
// Take the decimal part
if (number > 1) {
number = number - 1;
}
result = result + Math.floor(number * 2);
number = number * 2;
}
result = '0. + result;
return result;
};
/** * @name decimalToBinary * @description Positive/negative integer to binary * @param {any} number Number to be converted * @return Binary string */
const decimalToBinary = (number) = > {
let result = ' ';
if (Number.isInteger(number) && number >= 0) { / / positive integer
result = integerGEQZero(number);
} else if (Number.isInteger(number) && number < 0) { / / negative integer
result = integerLSSZero(number);
} else if (!Number.isInteger(number) && number > 0 && number < 1) { // Positive decimal (without integer bits)
result = floorBetweenZeroOne(number);
} else if (!Number.isInteger(number) && number > 1) { // Positive decimal (with integer bits)
result = floorGTROne(number);
}
return result;
};
// Integer to binary [0, n]
console.log(decimalToBinary(10)); / / 1010
console.log(decimalToBinary(42)); / / 101010
// Negative integer to binary [n, 0]
console.log(decimalToBinary(- 10)); / / 11110110
console.log(decimalToBinary(- 42)); / / 11010110
// From decimal to binary (0, 1)
console.log(decimalToBinary(0.125)); / / 0.001
console.log(decimalToBinary(0.8125)); / / 0.1101
// From decimal to binary (1, n)
console.log(decimalToBinary(6.125)) / / 110.001
console.log(decimalToBinary(173.8125)) / / 10101101.1101
Copy the code
Five binary to decimal
Attention! The conversion of binary to decimal here includes:
- Positive integer [0, n]
- Negative integer [n, 0]
- The decimal (0, 1)
- The decimal (1, n)
It doesn’t include negative decimals. It doesn’t include negative decimals. It doesn’t include negative decimals
This is actually the inverse of the calculation of the code above… But it’s tiring to push back
/** * @name stringDifference * @description String difference * @param {string} a subtraction one * @param {string} b subtraction two * @param {any} base Base (default decimal) * @return Returns the calculation result */
const stringDifference = (a = ' ', b = ' ', base = 10) = > {
/ / the result
let result = ' ';
// The borrowing flag
let carry = 0;
// Set the length of a and b to facilitate reverse traversal
let aIndex = a.length - 1, bIndex = b.length - 1;
while (aIndex >= 0 || bIndex >= 0) { // We can subtract a and b
// Determine whether you need to borrow
let reduce = 0;
if ((+a[aIndex] || 0) < (+b[bIndex] || 0)) {
reduce = (+a[aIndex] || 0) + base - (+b[bIndex]);
carry = 1;
} else {
reduce = (+a[aIndex] || 0) - (+b[bIndex] || 0) - carry;
carry = 0;
}
// Calculate the final result
result = reduce % base + result;
// Move to a higher position
aIndex--;
bIndex--;
}
// Return the final result
return result;
};
* EQU - equal to: equal * NEQ - not equal * LSS - less than: less than * LEQ - less than or equal to: Equal or less than * GTR - Greater than * GEQ - Equal or greater than */
/** * @name integerLEQZero * @description A binary greater than or equal to 0 is converted to an integer * @param {string} binary * @return an integer */
const integerGEQZero = (binary) = > {
let result = 0;
const index = binary.indexOf('1');
const newBinary = binary.slice(index).split(' ').reverse(' ').join(' '); // cut after 1, and then from the end forward
for (let i = 0; i < newBinary.length; i++) {
result += newBinary[i] * Math.pow(2, i);
}
return result;
};
/** * @name integerLSSZero * @description Converts a binary less than 0 to an integer * @param {string} binary * @return integer */
const integerLSSZero = (binary) = > {
let result = 0;
/ / minus one
binary = stringDifference(binary, '1'.2);
let reverseBinary = ' '; / / the not
for (let i = 0; i < binary.length; i++) {
if (binary[i] === '0') {
reverseBinary += '1';
} else {
reverseBinary += '0';
}
}
result = -(integerGEQZero(reverseBinary));
return result;
};
/** * @name floorGTROne * @description > 1 * @param {string} binary * @return decimal */
const floorGTROne = (binary) = > {
let result = 0;
const [integer, decimal] = binary.split('. ');
result = integerGEQZero(integer) + floorBetweenZeroOne('0. + decimal);
return result;
};
/** * @name floorBetweenZeroOne * @description > 0 > 1 decimal * @param {string} binary * @return decimal */
const floorBetweenZeroOne = (binary) = > {
let result = 0;
binary = binary.replace('. '.' '); // Remove the decimal point
for (let i = 0; i < binary.length; i++) {
result += Number(binary[i]) * Math.pow(2, -i);
}
return result;
};
/** * @name binaryToDecimal * @description Binary to decimal * @param {string} binary * @return Decimal integer */
const binaryToDecimal = (binary) = > {
let result = 0; // Set the result set
if(! binary.includes('. ')) { // No decimal point
// If there are less than 8 bits, complete 8 bits
if (binary.length < 8) {
binary = '0'.repeat(8 - binary.length) + binary;
}
if (binary[0= = ='0') { // the first digit is a positive integer [0, n]
result = integerGEQZero(binary);
} else if (binary[0= = ='1') { // the first digit is a negative integer [n, 0]result = integerLSSZero(binary); }}else { // with decimal point
if (binary.split('. ') [0= = ='0') { // If the integer part is only 0 (0, 1)
result = floorBetweenZeroOne(binary);
} else { // If the integer part is greater than 0 (1, n)result = floorGTROne(binary); }}return result;
};
// Binary integer [0, n]
console.log(binaryToDecimal('1010')); / / 10
console.log(binaryToDecimal('101010')); / / 42
// Binary to negative integer [n, 0]
console.log(binaryToDecimal('11101011')); / / - 21
console.log(binaryToDecimal('11110110')); / / - 10
console.log(binaryToDecimal('11010110')); / / - 42
// Binary to decimal (0, 1)
console.log(binaryToDecimal('0.001')); / / 0.125
console.log(binaryToDecimal('0.1101')); / / 0.8125
// Binary to decimal (1, n)
console.log(binaryToDecimal('110.001')); / / 6.125
console.log(binaryToDecimal('10101101.1101')); / / 173.8125
Copy the code
Six summarize
Above, is this exploration ~
Yes, without any explanation…
You can eat it in combination with Plus minus:
- Github.com/LiangJunron…
If you find this article wrong, please correct it
Do not toss the front end, and what is the difference between salted fish!
Jsliang will update a LeetCode problem every day, so as to help friends consolidate the foundation of native JS, understand and learn algorithms and data structures.
Prodigal Excalibur will update the interview questions every day to drive everyone to study, keep learning and thinking every day, and make progress every day!
Scan the qr code above, pay attention to the jsliang public account (left) and prodigal Son Excalibur public account (right), let us toss together!
Jsliang’s document library is licensed by Junrong Liang under the Creative Commons Attribution – Non-commercial – Share alike 4.0 International License. Based on the github.com/LiangJunron… On the creation of works. Outside of this license agreement authorized access can be from creativecommons.org/licenses/by… Obtained.