标签:style blog http io ar color os sp for
题目:
Implement atoi to convert a string to an integer.
---- 实现atoi函数,此函数的功能是将一个字符串转换成一个整数。
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
注意点:主要是整数的最大值和最小值的情况处理。
思路:扫描整个字符串,处理空格,处理符号,处理数字字符(*str - ‘0‘)。
来源:https://oj.leetcode.com/problems/string-to-integer-atoi/
参考代码:
1 class Solution { 2 private: 3 int MAX_ACTIVE_INT = 2147483647; 4 int MIN_NEGTIVE_INT = -2147483648; 5 public: 6 7 int atoi(const char *str) 8 { 9 int result = 0; 10 int sign = 1; 11 if(str == NULL || strlen(str) == 0) { 12 return 0; 13 } 14 15 /*escape the space*/ 16 while(*str != ‘\0‘) { 17 if(isspace(*str)) { 18 str++; 19 } 20 else{ 21 break; 22 } 23 24 } 25 /* deal with the sign */ 26 if(*str == ‘+‘ || *str == ‘-‘) { 27 if(*str == ‘-‘) { 28 sign = -1; 29 } 30 str++; 31 } 32 while(*str != ‘\0‘) { 33 if(isdigit(*str)) { 34 int digit = *str - ‘0‘; 35 /*deal with the max integer*/ 36 if(sign*result > (MAX_ACTIVE_INT - digit) / 10) { 37 return MAX_ACTIVE_INT; 38 } 39 /*deal with the min integer */ 40 else if(sign*result < (MIN_NEGTIVE_INT + digit) / 10) { 41 return MIN_NEGTIVE_INT; 42 } 43 result = result * 10 + digit; 44 str++; 45 } 46 else{ 47 break; 48 } 49 } 50 return result * sign; 51 } 52 };
时间复杂度为O(n),n为字符串长度。
String to Integer (atoi)---将字符串转变成整数
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/cloudfeng/p/4138446.html