Interview Questions

What subtleties you will look for while writing an atoi program? ......

Microsoft Interview Questions and Answers


(Continued from previous question...)

133. What subtleties you will look for while writing an atoi program? ......

Question:
What subtleties you will look for while writing an atoi program? How will you detect overflow? Write a program to add two numbers represented in string and return the sum as string.


maybe an answer:


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
string a="3";
string b="65";
int sum=atoi(a.c_str())+atoi(b.c_str());

char Ssum[sizeof(sum)];
itoa(sum,Ssum,10);
string s=Ssum;
cout<<s;
int d;
cin>>d;
return 0;
}



maybe an answer2:


typedef enum{false, true} bool;
int __atoi__(const char *str)
{
bool isNeg = false;
if(str[0] == '-')isNeg = true;
int result = 0;
int len = strlen(str);
int i;

for(i=isNeg; i<len; i++)
{
int digit = str[i]-'0';
if(isNeg)
{
if(result <(INT_MIN+digit)/10)return INT_MIN;
else result = result*10-digit;
}
else
{
if(result > (INT_MAX-digit)/10)return INT_MAX;
else result = result*10 + digit;
}
}

return result;
}

(Continued on next question...)

Other Interview Questions