write function atoi

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>
#include <math.h>
double natoi(const char* ch) {
std::string number(ch, ch+strlen(ch));
boost::regex re("^.*(\\+|\\-|[0-9]).*([^0-9]).*$");
if (boost::regex_match(number, re)) {
return 0;
}
double result = 0;
int position = 0;
if ('+' == number.at(0) || '-' == number.at(0)) {
position++;
}
for(std::string::iterator itr = number.begin() + position; itr!=number.end(); itr++) {
result += (int((*itr))-int('0'))*pow(10, number.end()-itr-1);
}
return ('-' == (number.at(0)) ? 0 - result : result);
}
int main() {
const char* str = "-11123";
if(natoi(str) == atoi(str)) {
std::cout<<"True"<<std::endl;
} else {
std::cout<<"False"<<std::endl;
}
return 0;
}