标签:
Implement atoi to convert a string to an integer.
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.
题目不难,一样要注意int的边界问题。
代码如下:
class Solution { public: int atoi(string str) { if (str.size() == 0) return 0; bool sign = false; long long num = 0; string::const_iterator iter = str.begin(); while (iter != str.end() && *iter == ‘ ‘){ ++iter; } if (iter == str.end()) return 0; if (*iter == ‘+‘ || *iter == ‘-‘){ if (*iter == ‘-‘) sign = true; iter++; } while (iter != str.end()){ if (*iter >= ‘0‘&&*iter <= ‘9‘){ num = num * 10 + *iter - ‘0‘; if (num > 2147483648){ num = 2147483648; break; } } else break; ++iter; } if (sign == true) num = 0 - num; else if (num == 2147483648) num--; return num; } };
标签:
原文地址:http://www.cnblogs.com/Scorpio989/p/4413790.html