首页 > 代码库 > 【LeetCode】8. String to Integer (atoi)
【LeetCode】8. String to Integer (atoi)
题目:
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.
虽然是个简单题,但是要考虑的细节挺多的,比如输入空串的话如何输出,输入有+,-号的话怎么办,如果遇到无效输入怎么办?数字溢出了该如何输出?如果遇到的是面试,最好都要弄清楚。
class Solution {public: int myAtoi(string str) { if (str == "") return 0; int flag = 1; int res = 0; string::const_iterator iter = str.begin(); while (*iter == ‘ ‘ && iter != str.end()) iter++; if (*iter == ‘+‘ || *iter == ‘-‘){ if (*iter == ‘-‘) flag = -1; *iter++; } while (iter!=str.end() && isValidNum(*iter)) { int tmp = *iter - ‘0‘; if (res > (INT_MAX - tmp) / 10 && flag == 1) return INT_MAX; if (res > (INT_MAX - tmp) / 10 && flag == -1) return INT_MIN; res = res * 10 + tmp; iter++; } return flag*res; } bool isValidNum(char c) { return c >= ‘0‘ && c <=‘9‘; }};
【LeetCode】8. String to Integer (atoi)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。