Problem
The first routine converts a string to a signed integer. You may assume that the string only contains digits and the minus character (‘-’), that it is a properly formatted integer number, and that the number is within the range of an int type. The second routine converts a signed integer stored as an int back to a string.
Solution
Start number at 0
If the first character is '-' Set the negative flag
Start scanning with the next character
For each character in the string
Multiply number by 10 Add (digit character – '0') to number
Return number
#include <iostream>
using namespace std;
int iatoi(char *str)
{
int ret = 0;
if(str == NULL){
return 0;
}
int sign = 1;
char *p = str;
if(*p == '-'){
sign = -1;
p++;
}
while(*p != '\0'){
ret *= 10;
ret += *p - '0';
p ++;
}
ret *= sign;
return ret;
}
int main(int argc, char* argv[])
{
char *str[10] = {
"-123",
"0",
"23403",
"-123"
};
for(int i = 0; i < 4; i++){
cout << str[i] << " -- " <<iatoi(str[i]) << endl;
}
}