Problem
Sheokand is good at mathematics. One day, to test his math skills, Kaali gave him an integer . To impress Kaali, Sheokand has to convert into an integer that can be represented in the form (where and are non-negative integers such that ). In order to do that, he can perform two types of operations:
- add to
- subtract from
However, Sheokand is preparing for his exams. Can you help him find the minimum number of operations required to convert into a valid integer ?
Input
- The first line of the input contains a single integer denoting the number of test cases. The description of test cases follows.
- The first and only line of each testcase contains a single integer .
Output
For each test case, print a single line containing one integer — the minimum required number of operations.
Constraints
Subtasks
Subtask #1 (30 points):
Subtask #2 (70 points): original constraints
Sample 1:
3 10 22 4
0 2 1
Explanation:
Example case 1: is already in the form , with and .
Example case 2: can be converted into or in two operations.
Example case 3: can be converted into or in one operation.
Program :
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
long n=sc.nextInt();
if(n==1)
{
System.out.println(2);
--t;
continue;
}
long a=2;
while(a<n) {
a*=2;
}
if(a==n)
{
System.out.println(1);
}
else
{
long ans=Math.min(Math.abs(a+1-n),Math.abs(n-(a/2+1)) );
long diff=a-a/2,p=2;
while(p<diff)
{
ans=Math.min(ans,Math.abs(a/2+p-n));
p=p<<1;
}
System.out.println(ans);
}
--t;
}
}
}
0 Comments