Firstly, I got the solution for this question in CodeChef, but I noticed one thing which still confuses me. This was the code which was accepted as correct.
#include<iostream>
using namespace std;
int main(){
int testCases,count=0;
cin>>testCases;
unsigned long int a,b;
while(testCases--){
count=0;
cin>>a>>b;
while(a&(a-1)){
a>>=1;
count++;
}
while(a>b){
a>>=1;
count++;
}
while(a != b){
a<<=1;
count++;
}
cout<<count<<"\n";
}
return 0;
}
And this is the solution which was getting TLE:
#include<iostream>
using namespace std;
int main(){
int testCases,count=0;
cin>>testCases;
unsigned long int a,b;
while(testCases--){
count=0;
cin>>a>>b;
while(a&(a-1) != 0 || a>b){
a>>=1;
count++;
}
while(a != b){
a<<=1;
count++;
}
cout<<count<<"\n";
}
return 0;
}
Both the solutions are almost same. What I have just modified in the first is that I have put a separate while
loop
- for checking if a is the power of 2
- for making value of a less than b
Now what I understood was that keeping separate while loop saves me time by NOT having to do two conditions check for each iteration.
Am I correct with this understanding, or I am missing something. If I am correct, is it good practice (as per optimization) to write separate loops.
I would like to know how I can write this code in a better way or what other good practice I can follow.