day 25: 338-valid-counting-bits, 167-two-sum-ii-input-array-is-sorted

This commit is contained in:
2023-10-24 19:29:54 -07:00
parent 8acacbbc59
commit 191a4262d0
6 changed files with 108 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
int n = 7;
vector<int> answer{0, 1, 1, 2, 1, 2, 2, 3};
Solution soln;
cout << "Counted bits correctly? " << soln.test(n, answer) << endl;
return 0;
}

View File

@@ -0,0 +1,37 @@
#include "soln.hpp"
vector<int> Solution::countBits(int n)
{
vector<int> result(n + 1);
// // O(n log n) approach, naive
// // O(n)
// int num;
// for(int i = 0; i <= n; i++) {
// num = i;
// // O(log n)
// while(num) {
// result[i] += num&1;
// num=num>>1;
// }
// }
// O(n) approach
result[0] = 0;
if (n == 0)
{
return result;
}
for (int i = 1; i < n + 1; i = i * 2)
{
for (int j = i; (j < i * 2) && (j < n + 1); j++)
{
result[j] = result[(j / i) + (j - i) - 1] + 1;
}
}
return result;
}
bool Solution::test(int n, vector<int> &answer)
{
return countBits(n) == answer;
}

View File

@@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> countBits(int n);
bool test(int n, vector<int> &answer);
};