myatoi
02 Jan 2012
|
#include <stdio.h>
#include <string.h>
#include <limits.h>
int myAtoi(char* str)
{
long num = 0;
int tag = 1;
const int n = strlen(str);
int i = 0;
while(str[i]==' ' && i < n) i++;
if(str[i] == '+') i++;
if(str[i] == '-') {i++; tag = -1;}
for(; i < n; i++) {
if(str[i] < '0' || str[i] > '9') break;
if(num > INT_MAX || num < INT_MIN)
return tag == 1? INT_MAX : INT_MIN;
num = num * 10 + str[i] - '0';
}
return (int)num * tag;
}
int main()
{
char str[] = "++1";
printf("%d\n", myAtoi(str));
return 0;
}
#include <iostream>
#include <string>
#include <limits.h>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
if(str.empty()) return 0;
int len = str.length();
long value = 0;
int tag, i = 0;
while(i < len && str.at(i) == ' ') i++;
if(i == len)
return 0;
else if(str.at(i) == '-') {
tag = -1;
i++;
} else if(str.at(i) == '+') {
i++;
}
while(i < len) {
if(str.at(i) < '0' || str.at(i) > '9') return int(value);
value = value * 10 + tag * (str.at(i) - '0');
if(value > INT_MAX) return INT_MAX;
else if(value < INT_MIN) return INT_MIN;
i++;
}
return (int)value;
}
};
int main()
{
Solution a;
cout << a.myAtoi("-33.5a") << endl;
return 0;
}