LeetCode 1356: Sort Integers by The Number of 1 Bits Solution
Master LeetCode problem 1356 (Sort Integers by The Number of 1 Bits), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1356. Sort Integers by The Number of 1 Bits
Problem Explanation
Explanation:
- We need to sort the given integers based on the number of set bits (1s) in their binary representation.
- We can achieve this by defining a custom comparator that compares the integers based on the count of set bits.
- If two integers have the same number of set bits, we sort them in ascending order.
- To count the number of set bits in an integer, we can use the built-in method like
Integer.bitCount()in Java, or use bitwise operations.
Solution Code
import java.util.*;
class Solution {
public int[] sortByBits(int[] arr) {
Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxedArr, (a, b) -> {
int countA = Integer.bitCount(a);
int countB = Integer.bitCount(b);
return countA == countB ? a - b : countA - countB;
});
return Arrays.stream(boxedArr).mapToInt(Integer::intValue).toArray();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1356 (Sort Integers by The Number of 1 Bits)?
This page provides optimized solutions for LeetCode problem 1356 (Sort Integers by The Number of 1 Bits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1356 (Sort Integers by The Number of 1 Bits)?
The time complexity for LeetCode 1356 (Sort Integers by The Number of 1 Bits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1356 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1356 in Java, C++, or Python.