标签:
字符串转为数字,细节题。要考虑空格、正负号,当转化的数字超过最大或最小是怎么办。
int atoi(char *str) { int len = strlen(str); int sign = 1; int num = 0; int i = 0; while (str[i] == ‘ ‘&& i < len)i++; if (str[i] == ‘+‘)i++; else if (str[i] == ‘-‘) { sign = -1; i++; } for (; i < len; i++) { if (str[i]<‘0‘&&str[i]>‘9‘)break; if (num>INT_MAX / 10 || (num==INT_MAX / 10 && (str[i] - ‘0‘)>INT_MAX % 10)) { return sign == -1 ? INT_MIN : INT_MAX; } num = num * 10 + str[i] - ‘0‘; } return num*sign; }
eetcode 之String to Integer (atoi)(28)
标签:
原文地址:http://www.cnblogs.com/573177885qq/p/5519567.html