题目:输入一个表示整数的字符串,把该字符串转换成整数并输出。
例如输入字符串"345",则输出整数345。
HANDWRITING:
int transform (string num) {
if (num.length() == 0) return 0;
string::iterator i = num.begin();
int flag = 1, n = 0;
if (*i == '-') { flag = -1; ++i; }
while (i != num.end()) {
n = n * 10 + *i++;
}
return flag * n;
}
1、char到int的转换要*i - '0',改正n = n * 10 + (*i++ - '0');
2、判断数字是否合法
ANSWER FROM:http://blog.csdn.net/v_july_v/article/details/6870251
This question checks how the interviewee is familiar with C/C++? I’m so bad at C/C++...
int atoi(char * str) {
int neg = 0;
char * p = str;
if (*p == ‘-’) {
p++; neg = 1;
} else if (*p == ‘+’) {
p++;
}
int num = 0;
while (*p != ‘\0’) {
if (*p>='0' && *p <= '9') {
num = num * 10 + (*p-’0’);
} else {
error(“illegal number”);
}
p++;
}
return num;
}
PS: I didn’t figure out how to tell a overflow problem easily.