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

Commit61a3d6b

Browse files
dp approach to counting bits
1 parente9f54b5 commit61a3d6b

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

‎MEDIUM/src/medium/CountingBits.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,21 @@ Space complexity should be O(n).
2727
*
2828
*/
2929
publicclassCountingBits {
30-
//TODO: follow its hint to solve it using DP
30+
privateclassDP_Solution{
31+
//lixx2100's post is cool:https://discuss.leetcode.com/topic/40162/three-line-java-solution
32+
//An easy recurrence for this problem is f[i] = f[i / 2] + i % 2
33+
//and then we'll use bit manipulation to express the above recursion function
34+
// right shift by 1 means to divide by 2
35+
//AND with 1 means to modulo 2
36+
//this is so cool!
37+
publicint[]countBits(intnum) {
38+
int[]ones =newint[num+1];
39+
for(inti =1;i <=num;i++){
40+
ones[i] =ones[i >>1] + (i&1);
41+
}
42+
returnones;
43+
}
44+
}
3145

3246

3347
//use the most regular method to get it AC'ed first
@@ -50,7 +64,7 @@ private int countOnes(int i) {
5064

5165
publicstaticvoidmain(String...strings){
5266
CountingBitstest =newCountingBits();
53-
intnum =5;
67+
intnum =15;
5468
int[]ones =test.countBits(num);
5569
CommonUtils.printArray(ones);
5670
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp