Created
July 18, 2022 15:42
-
-
Save mustafa-qamaruddin/3bf2077f15aeeae52c7364853512af56 to your computer and use it in GitHub Desktop.
338. Counting Bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
private int popCount(int x) { | |
int count; | |
for (count = 0; x != 0; ++count) { | |
x &= x - 1; // zeroing out the least significant nonzero bit | |
} | |
return count; | |
} | |
public int[] countBitsV1(int n) { | |
int[] ans = new int[n + 1]; | |
for (int x = 0; x <= n; ++x) { | |
ans[x] = popCount(x); | |
} | |
return ans; | |
} | |
public int[] countBitsV2(int n) { | |
int[] ans = new int[n + 1]; | |
int x = 0; | |
int b = 1; | |
// [0, b) is calculated | |
while (b <= n) { | |
// generate [b, 2b) or [b, n) from [0, b) | |
while (x < b && x + b <= n) { | |
ans[x + b] = ans[x] + 1; | |
++x; | |
} | |
x = 0; // reset x | |
b <<= 1; // b = 2b | |
} | |
return ans; | |
} | |
public int[] countBitsV3(int n) { | |
int[] ans = new int[n + 1]; | |
for (int x = 1; x <= n; ++x) { | |
// x / 2 is x >> 1 and x % 2 is x & 1 | |
ans[x] = ans[x >> 1] + (x & 1); | |
} | |
return ans; | |
} | |
public int[] countBits(int n) { | |
int[] ans = new int[n + 1]; | |
for (int x = 1; x <= n; ++x) { | |
ans[x] = ans[x & (x - 1)] + 1; | |
} | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment