We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 24141f6 commit 46ce1a9Copy full SHA for 46ce1a9
338.Counting Bits
@@ -0,0 +1,35 @@
1
+/*Explanation
2
+1. we are iterating till n;
3
+ for every i, we have to count 1's bits in its binary form.
4
+ 0 --> 0
5
+ 1 --> 1
6
+ 2 --> 10
7
+ 3 --> 11
8
+ 4 --> 100
9
+ 5 --> 101
10
+
11
+ Output: [0,1,1,2,1,2]
12
+ */
13
+class Solution {
14
+public:
15
+// T.C - o(nlog n)
16
+ vector<int> countBits(int n) {
17
+ vector<int>ans;
18
+ //loop ko 0 se n tak chalayenge
19
+ for(int i=0;i<=n;i++){
20
+ // sum is initialized as zero
21
+ int sum =0;
22
+ int num =i;
23
+ //while num not equals zero
24
+ while(num != 0){
25
+ //we have to count '1' s in binary representation of i, there fore % 2
26
+ sum += num%2;
27
+ num = num/2;
28
+ }
29
+ //add sum to ans vector
30
+ ans.push_back(sum);
31
32
+ //return
33
+ return ans;
34
35
+};
0 commit comments