Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Wayne, i think conversion doesnt mean to print as hex, but to give a logic to actually convert :)
static String toHex(int n) {
int mask = 15;
StringBuffer sb = new StringBuffer();
while (n != 0) {
int index = (n & mask);
char c = (char) ((index < 10) ? (index + '0') : ('A' + index - 10));
sb.append(c);
n = n >>> 4;
}
sb.reverse();
return sb.toString();
}
is there anything wrong with this code(assuming that its 32 bit integer that has to be converted to hexadecimal)
logic: each set of four bits corresponds to a hexadecimal digit, thus the four rightmost bit are collected through bit manipulation and converted to hexadecimal using lookup table.
char[] convert(int n){
mask= ~((~0)<<4);//makes rightmost 4 bits 1
char hex[8];//to store 8 digit hexadecimal
int digit=7;
while(n!=0){
int hex_bit=0;
hex_bit=mask&&no;//stores 4 righmost bits in hex_bit
hex[digit--]=convert_to_hex(hex_bit)//this function implements just a look up from
// 0 to 16 to convert decimal to hexa
n=n>>4;
}
while(digit>-1) hex[digit--]='0';//rest left most hexa digits are set to zero
}
is there anything wrong with this code(assuming that its 32 bit integer that has to be converted to hexadecimal)
logic: each set of four bits corresponds to a hexadecimal digit, thus the four rightmost bit are collected through bit manipulation and converted to hexadecimal using lookup table.
char[] convert(int n){
mask= ~((~0)<<4);//makes rightmost 4 bits 1
char hex[8];//to store 8 digit hexadecimal
int digit=7;
while(n!=0){
int hex_bit=0;
hex_bit=mask&&no;//stores 4 righmost bits in hex_bit
hex[digit--]=convert_to_hex(hex_bit)//this function implements just a look up from
// 0 to 16 to convert decimal to hexa
n=n>>4;
}
while(digit>-1) hex[digit--]='0';//rest left most hexa digits are set to zero
return hex;
}
is there anything wrong with this code(assuming that its 32 bit integer that has to be converted to hexadecimal)
logic: each set of four bits corresponds to a hexadecimal digit, thus the four rightmost bit are collected through bit manipulation and converted to hexadecimal using lookup table.
char[] convert(int n){
mask= ~((~0)<<4);//makes rightmost 4 bits 1
char hex[8];//to store 8 digit hexadecimal
int digit=7;
while(n!=0){
int hex_bit=0;
hex_bit=mask&&no;//stores 4 righmost bits in hex_bit
hex[digit--]=convert_to_hex(hex_bit)//this function implements just a look up from
// 0 to 16 to convert decimal to hexa
n=n>>4;
}
while(digit>-1) hex[digit--]='0';//rest left most hexa digits are set to zero
return hex;
}
Suppose that int is 32 bit (if not choose an integer-type that is)
1.
2.
- Selmeczy, Péter December 22, 2011