Counting Bits in Binary Representation

🚀 Solved LeetCode 338: Counting Bits 🚀 I recently worked on the Counting Bits problem, where the task is: 👉 Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 🔹 My Approach: Initialize an array of size n+1. For each number from 1 to n: Copy the number into a temporary variable. Use a loop to repeatedly divide by 2, counting the remainder (num % 2) each time. Store the total count of 1’s in the array. Return the final array. 📊 Complexity Analysis: Time Complexity: O(n log n) Each number requires about log(i) steps to process its binary digits. Space Complexity: O(n) Only the result array of size n+1 is used. ✨ Key Learning: This problem strengthened my understanding of binary representation and iterative problem solving. It was a great reminder that even simple bitwise operations can unlock powerful solutions. #LeetCode #Java #ProblemSolving #BackendDevelopment #CodingJourney #BitManipulation

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories