mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 25: 338-valid-counting-bits, 167-two-sum-ii-input-array-is-sorted
This commit is contained in:
10
338-counting-bits/driver.cpp
Normal file
10
338-counting-bits/driver.cpp
Normal 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;
|
||||
}
|
||||
37
338-counting-bits/soln.cpp
Normal file
37
338-counting-bits/soln.cpp
Normal 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;
|
||||
}
|
||||
8
338-counting-bits/soln.hpp
Normal file
8
338-counting-bits/soln.hpp
Normal 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);
|
||||
};
|
||||
Reference in New Issue
Block a user