Update formatting and description of some older math snippets

This commit is contained in:
Angelos Chalaris
2020-03-05 23:06:48 +02:00
parent 69db3851ff
commit 1b5b6d5deb
2 changed files with 7 additions and 5 deletions

View File

@ -1,11 +1,11 @@
--- ---
title: hammingDistance title: hammingDistance
tags: math,beginner tags: math,regexp,intermediate
--- ---
Calculates the Hamming distance between two values. Calculates the Hamming distance between two values.
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`. Use the XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
Count and return the number of `1`s in the string, using `match(/1/g)`. Count and return the number of `1`s in the string, using `match(/1/g)`.
```js ```js
@ -14,4 +14,4 @@ const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) |
```js ```js
hammingDistance(2, 3); // 1 hammingDistance(2, 3); // 1
``` ```

View File

@ -10,10 +10,12 @@ Use `Math.round()` to convert to an integer.
```js ```js
const toSafeInteger = num => const toSafeInteger = num =>
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); Math.round(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
``` ```
```js ```js
toSafeInteger('3.2'); // 3 toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991 toSafeInteger(Infinity); // 9007199254740991
``` ```