"Counting 1s in binary with DP and Python"

💡 Day 64 of #LeetCode365 Problem: 338. Counting Bits Category: Bit Manipulation | Dynamic Programming Today’s problem was all about counting 1s in binary numbers — basically, checking how “on” each number is 💡😅 💻 Approach: 👉 Use a DP array ans to store counts of 1s for each number. 👉 For each number: If it’s even ➡️ same count as i/2 If it’s odd ➡️ one more than (i−1) ans = [0, 1, 1] for i in range(3, n + 1): if i % 2 == 0: ans.append(ans[i // 2]) else: ans.append(ans[i - 1] + 1) return ans[:n + 1] ⚙️ Complexity: ⏱ O(n) | 💾 O(n) 💡 Lesson: Bits are like people — some are off, some are on, but together, they make the system work 😎💻 #LeetCode #Python #DynamicProgramming #BitManipulation #CodingHumor #100DaysOfCode #FunnyCode

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories