Apple Interview Question for Development Support Engineers






Comment hidden because of low score. Click to expand.
0
of 0 vote

// wrote C# code for this

static 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;
}

- KJ May 16, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

int 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);
}

- A^2 - Apple Aspirant June 02, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Above answer is "the" Correct answer. Using power is inefficient.

- Correct September 09, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

well this does not account -ve numbers..the sol must be modified to check if the MSB is 1 or 0

- Anonymous January 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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'))

- Bullocks December 29, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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))

- Bullocks December 29, 2009 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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++;
    }
}

- Anonymous October 07, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Out of curiosity, why use *hex++ instead of hex++?

- Anonymous May 19, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
}

- Anonymous June 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Anonymous July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
			
	}

- ATuring September 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{ #include <iostream> using namespace std; int htoi(char* c) { int result = 0; for(int i = 0; c[i] != '\0'; i++) { if(c[i] >= '0' && c[i] <= '9') { result = (result * 16) + c[i] - '0'; } else if(c[i] >= 'A' && c[i] <= 'F') { result = (result * 16) + c[i] - 'A' + 10; } else if(c[i] >= 'a' && c[i] <= 'f') { result = (result * 16) + c[i] - 'a' + 10; } else { cout << "Invalid character" << endl; return -1; } } return result; } int main() { char* c = "24D65"; cout << htoi(c) << endl; return 0; } - akshaycj47 November 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- Mayank Jain August 23, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

int htoi(string hex)
{
    int i,retv=0;
    
    for(i=0;i<hex.size();i++)
    {
      if(hex[i]>='A' && hex[i]<='F')
      {
      retv=retv*16+ (hex[i]-'A'+10);
      continue;
      }
      
      else
      retv=retv*16+ (hex[i]-'0' );
      
      }
      
      
      return retv;
      
      }

- Anonymous July 25, 2009 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More