Apple Interview Question
Development Support Engineersint power (int a, int b) // utility function
{
int res = 1 ;
while( b>0 )
{
res *= a ;
b--;
}
return ( res );
}
int htoi ( char* s )
{
int result = 0;
int value =0;
int len = strlen(s);
int exp = len;
char c;
int i;
for( i=0; i<len; i++)
{
c = s[i];
if ( c >='1' && c<='9')
new_result = (int)( (c - '0') * power(16, exp-1) );
else if (c >='A' && c<='F')
new_result = (int)( (c - 55) * power(16, exp-1) );
exp --;
result += new_result;
}
return (result);
}
Here's Python:
# efficient, lazy-evaluation of base powers
def pow(b):
p = 1
while 1:
yield p
p *= b
# pre-compute hashtable of hex digit conversions
def hexdigit2int_tbl():
xlat = {}
for i in range(10):
xlat[str(i)] = i
for i in range(6):
c = chr(ord('a')+i)
C = chr(ord('A')+i)
xlat[c] = xlat[C] = i+10
return xlat
# validate input hex string
# optional 2nd argument only evaluated once at first use
def is_hex(h, xlat=hexdigit2int_tbl()):
for d in h:
if d not in xlat:
return False
return True
def htoi(h, xlat=hexdigit2int_tbl()):
if not is_hex(h):
return None
return sum(xlat[d]*p for d, p in zip(h[::-1], pow(16)))
print(htoi('g')) # not hex, return None
print(htoi('123456789AbCdEf0'))
I should add, if I were to ignore checking of the hex string (which seems to be the prevailing practice here) and assume I'm given a pre-constructed hashtable of hex digit conversions, then the code shortens to the following:
# efficient, lazy-evaluation of base powers
def pow(b):
p = 1
while 1:
yield p
p *= b
def htoi(h, xlat):
return sum(xlat[d]*p for d, p in zip(h[::-1], pow(16)))
print(htoi('g', xlat)) # not hex, return None
print(htoi('123456789AbCdEf0', xlat))
assuming the string is in upper case
int htoi(char *hex)
{
int result = 0;
while (*hex) {
result = result * 16 + *hex - 'A' >= 0 ? *hex = 'A' + 10 : *hex - '0';
*hex++;
}
}
struct Foo{
char *pName;
char *pAddress;
};
main(){
struct Foo *obj = malloc(sizeof(struct Foo));
clrscr();
obj->pName = malloc(100);
obj->pAddress = malloc(100);
strcpy(obj->pName,"Your Name");
strcpy(obj->pAddress, "Your Address");
free(obj);
printf("%s", obj->pName);
printf("%s", obj->pAddress);
}
long htoi(NSString* hex)
{
NSString *h = [hex uppercaseString];
long result = 0;
for (int i = 0; i < hex.length; i++) {
unichar c = [h characterAtIndex:i];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
if(c >='A' && c <='F')
result=result * 16+ (c -'A'+10);
else
result=result * 16+ (c -'0');
}
else {
return -1;
}
}
return result;
}
Java Solution:
public void HexToInt(String s)
{
char[] cArr=s.toCharArray();
HashMap<Character, Integer> hexVal=new HashMap<Character,Integer>();
hexVal.put('A', 10);
hexVal.put('B', 11);
hexVal.put('C', 12);
hexVal.put('D', 13);
hexVal.put('E', 14);
hexVal.put('F', 15);
int intVer=0;
int counter=0;
for(int i=cArr.length-1; i>=0; i--)
{
if(hexVal.containsKey(cArr[i]))
{
intVer=intVer+ (int) Math.pow(16, counter)*hexVal.get(cArr[i]);
}
else
{
intVer=intVer+((int) Math.pow(16, counter))*Character.getNumericValue(cArr[i]);
}
counter++;
}
System.out.println("\nhexToInt:" + intVer);
}
public class HexaDecimalToInteger {
public static void convertToDecimal(String hexStr){
int maxPower = hexStr.length()-1;
int sum=0;
for(int i=0;i<=hexStr.length()-1;i++){
int digit=0;
if(hexStr.charAt(i) >= '0' && hexStr.charAt(i) <= '9'){ // between 0 and 9
digit = hexStr.charAt(i) - '0';
}else{ // between A and E
digit = 10 + (hexStr.charAt(i) - 'A');
}
sum = sum*16 + digit; // optimized way to convert
}
System.out.println("Decimal : " + sum);
}
public static void main(String[] args) {
String hexStr ="23AE";
convertToDecimal(hexStr);
}
}
// wrote C# code for this
- KJ May 16, 2009static int PowerTO16(int power) //helper function
{
int num = 1;
while (power > 0)
{
num *= 16;
power--;
}
return num;
}
static int htoi(string str)
{
int length = str.Length;
int power = 0;
int num = 0;
int sum = 0;
for (int i = length - 1; i >= 0; i--)
{
if (str[i] >= '0' && str[i] <= '9')
{
num = (Convert.ToInt32(str[i] - '0') * PowerTO16(power));
}
else if ((str[i] - 'A') >= 0 && (str[i] - 'F') <= 0)
{
int s = str[i] - 'A';
s += 10;
num = s * PowerTO16(power);
}
else
return Int32.MinValue;
sum += num;
power++;
}
return sum;
}