Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb97047d

Browse files
counting bits
1 parent328871c commitb97047d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎MEDIUM/src/medium/CountingBits.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
packagemedium;
2+
3+
importutils.CommonUtils;
4+
5+
/**338. Counting Bits QuestionEditorial Solution My Submissions
6+
Total Accepted: 37328
7+
Total Submissions: 64455
8+
Difficulty: Medium
9+
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
10+
11+
Example:
12+
For num = 5 you should return [0,1,1,2,1,2].
13+
14+
Follow up:
15+
16+
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
17+
Space complexity should be O(n).
18+
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
19+
20+
Hint:
21+
22+
You should make use of what you have produced already.
23+
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
24+
Or does the odd/even status of the number help you in calculating the number of 1s?
25+
26+
*
27+
*
28+
*/
29+
publicclassCountingBits {
30+
//TODO: follow its hint to solve it using DP
31+
32+
33+
//use the most regular method to get it AC'ed first
34+
publicint[]countBits(intnum) {
35+
int[]ones =newint[num+1];
36+
for(inti =0;i <=num;i++){
37+
ones[i] =countOnes(i);
38+
}
39+
returnones;
40+
}
41+
42+
privateintcountOnes(inti) {
43+
intones =0;
44+
while(i !=0){
45+
ones++;
46+
i &= (i-1);
47+
}
48+
returnones;
49+
}
50+
51+
publicstaticvoidmain(String...strings){
52+
CountingBitstest =newCountingBits();
53+
intnum =5;
54+
int[]ones =test.countBits(num);
55+
CommonUtils.printArray(ones);
56+
}
57+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp