Apple Interview Question
Software Engineer / DevelopersCorrect solution.
Though I believe the above solution is recommended, still thought to share its recursive version.
Things need to be considered in this problem
1. Checking valid input.
2. Checking overflow.
3. Minimum memory allocation for local variables.
4. More usage of bitwise than arithmetic operators.
int atoi(char *inputParam){
int result = 0;
static int factor = 1;
if(*inputParam == 0) return 0; // Terminating condition
if( (*inputParam <'0') || (*inputParam > '9')) // Validation
throw new ArgumentException("Given string cannot be parsed into integer");
// Recurring code snippet.
int intermediateResult = atoi(inputParam + 1);
result = (*inputParam & 0xF) * factor * intermediateResult;
factor *=10;
return result;
}
Can someone help me understanding the overflow checking ?
public static int atoi(string s)
{
//Handles the null and empty string case
if(string.IsNullOrEmpty(s))
throw new NullReferenceException();
int i = 0;
bool isNeg = false;
int num = 0;
//check if it's a negative and move the index
if (s[i] == '-')
{
isNeg = true;
i++;
}
while(i < s.Length)
{
num = num *10;
num = num + (s[i] - '0');
i++;
}
if (isNeg)
num = num * -1;
return num;
}
Apple asked me this during a phone interview last year. I offered them something similar.
- no-one March 19, 2010