Skip to content

Commit

Permalink
Leetcode: 1356 sort integers by the number of 1 bits
Browse files Browse the repository at this point in the history
  • Loading branch information
herrera-ignacio committed Oct 30, 2023
1 parent e6a4105 commit 92a6e23
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions problems/leetcode/1356/solution.js
Original file line number Diff line number Diff line change
@@ -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;
}
});
}

0 comments on commit 92a6e23

Please sign in to comment.