I am getting timelimit exceeded error for this code:-
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int q = scn.nextInt();
while(q>0){
int count=0;
int a = scn.nextInt();
int b = scn.nextInt();
for(int i=a;i<=b;i++){
while(i!=0){
if((i&1)!=0){
count++;
}
i=(i>>1);
}
}
System.out.println(count);
q–;
}
}
}
Playing with bits challenge error
its like u have Q queuries (likeT test cases)
for each test case you are given a and b
you have to iterate from a to b ( both inclusive) and then for each integer b/w a & b you simply add up count no of set bits in each
and print the count at the end
Log(n) per query.
We have to find set bit between a and b.
So we find set bit between 1 to b then 1 to a in log(n) then find the difference.
( its simply asking u to write optimised code for counting no of set bits)
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.