Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
well, this is a standard trick to get your
data aligned by double-word boundary, i.e.: (x + 7) & ~7
Hmmm...if you used an and mask, this could in theory be just 2 assembly instructions. This may or may not be more efficient than the previous best solution.
Its a binary number given. Binary of 8 is 1000. So anything less than 1000, the answer is 1000.
For any binary having more than 4 digits; make the last three digits as 0 and add 1.
Example:
Dec 30; Bin 11110.
Make last three digits as 0 - 11000
Add 1 - 11000 + 1 = 100000; Bin 100000 = Dec 32.
<pre lang="" line="1" title="CodeMonkey74213" class="run-this">import java.io.*;
class shiftjava
{
public static void main(String args[]) throws Exception // Basic idea: consider 17 => result must be 24(i.e)16+8
{
int flag=0;
DataInputStream d=new DataInputStream(System.in);
System.out.print("Enter the no. : ");
int e=Integer.parseInt(d.readLine());
if(e<0) //Negative no. check
{
e*=-1; //Convert to positive
flag=1;
}
int temp=e/8; // 17/8 =2
temp=temp*8; // 2*8 = 16
e=e&temp; // 17 - 10001 ; 16 - 10000 hence 17&16= 10000(16)
e+=8;//16+8
if(flag==1)//for negative no's
e*=-1;
System.out.println(e);//Integer.toBinaryString(e) -- to convert to binary form
}
}</pre><pre title="CodeMonkey74213" input="yes">
</pre>
0 = 00 - 0000
8 = 00 - 1000
16 = 01 - 0000
24 = 01 - 1000
32 = 10 - 0000
40 = 10 - 1000
My solution would be
static int GetNearest8(int n)
{
int LASTBITS = n & 0XF;
int GreatHalf = n ^ LASTBITS;
int retVal= 0;
if ((LASTBITS < 8) && (LASTBITS > 0))
retVal = GreatHalf + 0X8;
else
{
int temp = GreatHalf >> 4;
temp++;
GreatHalf = temp << 4;
retVal = GreatHalf;
}
return retVal;
}
// the next one that is multiple of 8 is arrived by increase bit 3
// and make the bit 0 ~ 2 becomes 0
// the previous one is just arrived by just making bit 0 ~ 2 become 0
// to determine which one to return, if bit 2 is 1 meaning it is closer
// to next one, if bit 2 is 0, it is closer to previous one
public static int findNext (int n){
return ((1<<2) & n) !=0 ? ((n + 8) & (~7)) : ((n) & (~7));
}
- Anonymous October 23, 2011