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.
spoilers alert… click to show requirements for atoi.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
字符串转化成整形,要求从第一个不是空格的字符开始算,最长的连续的一串可以转化成int类型的子串,这个子串如果能转化成int类型可以表示的数字就返回该数字,如过不可以就返回0。比如:“ 2132141dasfas123123”返回2132141,“dasas12412412”返回0,当然如果子串是以“-”“+”开头的话就要看后面的字符情况。

【解题思路】做完这个题目后看了discuss中得分很高的一个C++写法,这个写法非常简单,用了C++标准库的Stringstream中流之间的输入输出来控制类型的转化,所以精髓还在于对流的输入输出理解。

【考查内容】字符串

class Solution {
public:
int atoi(const char *str) {
int out = 0;
stringstream ss;
ss << str;
ss >> out;
return out;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值