diff --git a/README.md b/README.md index cc0d5b9..6f92fba 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,7 @@ - [1235: Maximum profit in job scheduling](problems/leetcode/1235) - Dynamic Programming + Binary Search - [1239: Maximum length of a concatenated string with unique characters](problems/leetcode/1239) - [1323: Maximum 69 number](problems/leetcode/1323) +- [1356: Sort integers by the number of 1 bits](problems/leetcode/1356) - [1509: Minimum difference between largest and smallest value in three moves](problems/leetcode/1509) - [1544: Make the string great](problems/leetcode/1544) - [1706: Where will the ball fall](problems/leetcode/1706) diff --git a/problems/leetcode/1356/solution.js b/problems/leetcode/1356/solution.js new file mode 100644 index 0000000..65850aa --- /dev/null +++ b/problems/leetcode/1356/solution.js @@ -0,0 +1,17 @@ +/** + * Note: assumes numbers are positive. The used binary conversion method + * doesn't work properly for negative numbers due to how JS represents them. + * @param {number[]} arr + * @return {number[]} + */ +const sortByBits = (arr) => { + return arr.sort((a, b) => { + const aPositiveBits = a.toString(2).split('1').length - 1; + const bPositiveBits = b.toString(2).split('1').length - 1; + if (aPositiveBits === bPositiveBits) { + return a - b; + } else { + return aPositiveBits - bPositiveBits; + } + }); +}