"Sorting integers by 1 bits in binary representation"

🚀 Day 42 of #100DaysOfCode – LeetCode Problem #1356: Sort Integers by The Number of 1 Bits 💬 Problem Summary: Given an integer array arr, sort the integers in ascending order by the number of 1’s in their binary representation. If two or more integers have the same number of 1’s, sort them in ascending numerical order. 🧩 Example: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explanation: 0 -> 0 bits 1,2,4,8 -> 1 bit 3,5,6 -> 2 bits 7 -> 3 bits 🧠 Logic: ✅ Count the number of 1s in each number’s binary form. ✅ Sort by (1) number of 1s, then (2) value. 💡 Key trick: Use the bit manipulation technique num &= (num - 1) to count set bits efficiently. 💻 Java Solution: class Solution { public int[] sortByBits(int[] arr) { Arrays.sort(arr, (a, b) -> { int countA = countBits(a); int countB = countBits(b); if (countA == countB) return a - b; return countA - countB; }); return arr; } private int countBits(int num) { int count = 0; while (num > 0) { num &= (num - 1); count++; } return count; } } ⚙️ Complexity: Time: O(n log n) (due to sorting) Space: O(1) ✅ Result: Accepted (Runtime: 1 ms) 💬 Takeaway: This problem beautifully combines sorting logic with bitwise manipulation. It’s a reminder that knowing how data is represented at the binary level gives you powerful optimization tools 

To view or add a comment, sign in

Explore content categories