Amazon Interview Question
Software Engineer in Testsint atoi(char* numberstr){
int num=0;
bool sign =false;
int length = getLength(numberstr);
if(numberstr[0]='-'){
sign = true;
numberstr++;
length--;
}
while(*numberstr){
num = (*numberstr - '0')*(length--);
numberstr++;
}
if(sign) num = num*(-1);
return num;
}
The code above reads the number from the string from left to right, setting the sign flag if the first character is '-'.
<pre lang="" line="1" title="CodeMonkey82292" class="run-this">#include <stdio.h>
#include <ctype.h>
#include <errno.h>
int myatoi(const char *src)
{
int c;
int total;
int sign;
int overflow = 0;
int max = 0x7FFFFFFF / 10;
while(isspace((int)(unsigned char)*src))
++src;
c = (int)(unsigned char)*src++;
sign = c;
if(c == '-' || c == '+')
c = (int)(unsigned char)*src++;
total = 0;
while(isdigit(c))
{
if(total > max) { overflow = 1; break; }
total = 10 * total + (c - '0');
c = (int)(unsigned char)*src++;
}
if(overflow) {
errno = ERANGE;
return 0x7FFFFFFF;
}
if(sign == '-')
return -total;
else
return total;
}
int main() {
char src[100];
while(scanf("%s", src))
printf("%d\n", myatoi(src));
}
</pre><pre title="CodeMonkey82292" input="yes">
</pre>
i think this can work too. i have also tested this and this worked. if there is any mistake then please point it out. all constructive comments are welcome.
public static int atoi(String a){
char[] arr = a.toCharArray();
int result = 0;
for(int i=0; i<arr.length; i++){
int k = (int) arr[i];
k = k-48;
result = (result*10)+k;
}
return result;
}
read each character and get its numerical equivalent by subracting the ascii value of '0' from the ascii value of the character.
- bob March 05, 2011build the number using a loop and multiplying by 10 and adding it to the already formed number.
reverse the number at the end(since we read the number in reverse from the char*)