01. Counting Bits
My Approach
1. We can count number of bits by iterating every number till n and count each set bits in every number
Time and Auxiliary Space Complexity
Code (C++)
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans;
for(int i=0;i<=n;i++){
int x = i;
int one =0;
while(x){
if(x&1) one++;
x /=2;
}
ans.push_back(one);
}
return ans;
}
};2. Optimized approch
Time and Auxiliary Space Complexity
Code (C++)
Contribution and Support
Last updated