Amazon Interview Question
Software Engineer in Testspublic static ArrayList<Integer> GetTheArray(int num)
{
if (num == 0)
return null;
ArrayList<Integer> result=new ArrayList<Integer>();
if (num == 1)
{
//result = new int[1];
result.add(1);
return result;
}
int multiplier = 2;
//result = new int[];
result.add(1);
for (int i = 1; i < num; i++)
{
int prev = result.get(i - 1);
int next = prev * multiplier;
if (next < num)
{
result.add(next);
}
else
{
break;
}
}
return result;
}
public static ArrayList<Integer> GetTheArray(int num)
{
if (num == 0)
return null;
ArrayList<Integer> result=new ArrayList<Integer>();
if (num == 1)
{
//result = new int[1];
result.add(1);
return result;
}
int multiplier = 2;
//result = new int[];
result.add(1);
for (int i = 1; i < num; i++)
{
int prev = result.get(i - 1);
int next = prev * multiplier;
if (next < num)
{
result.add(next);
}
else
{
break;
}
}
return result;
}
while( true ){
if( (i & ~( k-1 )) > 0){
System.out.println(" " + k);
}
if( k>i)
break;
k=k<<1;
}
where i is the input.
static int[] container;
static void Main(string[] args)
{
int i = 2, k =0;
int num =300;
container = new int[30];
container[k++] = i;
while (true)
{
i = i << 1;
if (i < num)
{
container[k++] = i;
}
else
{
break;
}
}
for (int j = 0; j < k; j++)
{
Console.WriteLine(container[j]);
}
Console.ReadKey();
-------------------------------------------------------------------------------------
- rits August 31, 2010Questions:
1. How do I reduce the result array size? I took an initial array size of num /2 since it will never exceed the num /2 size. But how do we optimize it more?
2. Is this function thread safe if multiple users access this function at the same time?