Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description…
- User
Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description Editorial Editorial Solutions Solutions Submissions Submissions Code Note Note Testcase Testcase Test Result 338. Counting Bits Easy Topics Companies Hint
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.
Example 1:
Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10
Example 2:
Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101
Constraints:
0 <= n <= 105
Follow up:
It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)? Seen this question in a real interview before? 1/5 Yes No Accepted 1.2M Submissions 1.5M Acceptance Rate 79.0% Topics Dynamic Programming Bit Manipulation Companies 0 - 6 months Amazon 4 6 months ago Adobe 7 Bloomberg 6 Google 5 Uber 5 Meta 3 Yahoo 3 Microsoft 2 Apple 2 Nvidia 2 Hint 1 You should make use of what you have produced already. Hint 2 Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Hint 3 Or does the odd/even status of the number help you in calculating the number of 1s? Similar Questions Number of 1 Bits Easy Sum of Values at Indices With K Set Bits Easy Find the K-or of an Array Easy Discussion (87) Choose a type Preview Comment 💡 Discussion Rules
-
Please don't post any solutions in this discussion.
-
The problem discussion is for asking questions about the problem or for sharing tips - anything except for solutions.
-
If you'd like to share your solution for feedback and ideas, please head to the solutions tab and post it there.
Sort by:Best No comments yet. 1 2 3 4 5 6 9 Copyright ©️ 2024 LeetCode All rights reserved 11.2K 87 Java Auto 1 2 3 4 5 class Solution { public int[] countBits(int n) { } } Saved Ln 1, Col 1 You must run your code first
Integer to English Words - LeetCode
Problem List Tag 264. Ugly Number II
Med.
- Paint House II
Hard
- Palindrome Permutation
Easy
- Palindrome Permutation II
Med.
- Missing Number
Easy
- Alien Dictionary
Hard
-
- Assistant
The programming question is:
338. Counting Bits
Description:
Given an integer
n, return an arrayansof lengthn + 1such that for eachi(0 <= i <= n),ans[i]is the number of 1's in the binary representation ofi.Examples:
Example 1: Input:
n = 2Output:[0, 1, 1]Explanation:- 0 has 0 ones.
- 1 has 1 one.
- 2 has 10 in binary which has 1 one.
Example 2: Input:
n = 5Output:[0, 1, 1, 2, 1, 2]Explanation:- 0 has 0 ones.
- 1 has 1 one.
- 2 has 10 in binary which has 1 one.