Microsoft Interview Question
/* Create your own atoi() function */
#include <stdio.h>
#include <string.h>
int myatoi(char* buf);
int main()
{
char buf[20] = {0};
printf("Enter a number: ");
scanf("%s",buf);
int i = myatoi(buf);
printf("myatoi() returned [%d]\n", i);
return 0;
}
int myatoi(char* buf)
{
int sum = 0;
int mult = 1;
int currVal = 0;
int nCount = strlen(buf);
for( int i = nCount-1; i >= 0; i-- )
{
if( i == 0 && buf[i] == '-' )
{
sum *= -1;
}
else
{
currVal = buf[i] - '0';
currVal *= mult;
sum += currVal;
mult *= 10;
}
}
return sum;
}
- Invalid character
- Overflow exception
- Positive and Negative numbers.
int MyAtoi(char *inputParam){
if(*inputParam == 0) throw new FormatException();
int result = 0;
bool isNegative = false;
if(*inputParam == '-'){
inputParam++;
isNegative = true;
}
if(*inputParam == 0) throw new FormatException();
while(*inputParam){
if(*inputParam >= 0x32 && *inputParam < 0x3C){
int tempResult = (result
+ (*inputParam - 0x32)
)
* ((*(inputParam + 1) == 0) ? 1 : 10);
if(tempResult < result) throw new OverflowException();
result = tempResult;
} else {
throw new FormatException();
}
}
return result;
}
- Invalid character
- Overflow exception
- Positive and Negative numbers.
int MyAtoi(char *inputParam){
if(*inputParam == 0) throw new FormatException();
int result = 0;
bool isNegative = false;
if(*inputParam == '-'){
inputParam++;
isNegative = true;
}
if(*inputParam == 0) throw new FormatException();
while(*inputParam){
if(*inputParam >= 0x32 && *inputParam < 0x3C){
int tempResult = (result
+ (*inputParam - 0x32)
)
* ((*(inputParam + 1) == 0) ? 1 : 10);
if(tempResult < result) throw new OverflowException();
result = tempResult;
} else {
throw new FormatException();
}
}
return result * (isNegative ? -1:1);
}
int rec_atoi(char *str,int *n){
int mul = 1;
if( *str != '-' &&(str == NULL || *str>'9' || *str <'0')){
*n = 0;
return 1;
}
else if( *str <='9' && *str >='0'){
mul = rec_atoi(str+1,n);
*n += (*str-'0')*mul;
return mul*10;
}
else if(*str == '-'){
mul = rec_atoi(str+1,n);
*n = *n*(-1);
return 1;
}
}
void main(){
int n = 0;
rec_atoi("110352a2a",&n);
printf(" %d \n ",n);
}
int atoi(char* str)
- mandeepg August 25, 2010{
int ret=0, i=0, flag=0;
if(str == NULL)
return -1;
if(str[0] == '-')
{
flag = 1;
i++;
}
while(str[i] != '\0')
{
if(!(str[i]>=48 && str[i]<=57))
return -1;
ret = ret * 10 + ((int)str[i] - '0');
i++;
}
return !flag ? ret : ret*-1;
}