Im am solving Count total set bits:
Find the sum of all bits from numbers 1 to N.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N.
Output:
Print the sum of all bits.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 1000Example:
Input:
2
4
17Output:
5
35Explanation:
An easy way to look at it is to consider the number, n = 4:
0 0 0 = 0
0 0 1 = 1
0 1 0 = 1
0 1 1 = 2
1 0 0 = 1
Therefore , the total number of bits is 5.
My approach:
/*package whatever //do not write package name here */
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class GFG {
private static int noOfBits (int N)
{
int sum = 0;
for (int i = 1; i <= N; i++)
{
if ((i & i-1) == 0)
{
sum += 1;
}
else
{
sum += numBits(i);
}
}
return sum;
}
private static int numBits (int num)
{
int sum = 0;
int rem;
while (num != 0)
{
rem = num%2;
num /= 2;
sum += rem;
}
return sum;
}
public static void main (String[] args) throws IOException {
//code
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
String line = br.readLine();
int T = Integer.parseInt(line);
String line2;
int N;
for (int i = 0; i < T; i++)
{
line2 = br.readLine();
N = Integer.parseInt(line2);
System.out.println(noOfBits(N));
}
}
}
I have the following questions with regards to the above code:
How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?