[LeetCode] 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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.


要解决这个问题最关键的部分就在于要考虑到所有可能的输入并从中判断出合法的输入。

首先如果字符串开头有空白则需要把空白部分给跳过。

因为atoi函数是转换字符串开头部分的数字为整型,因此合法的输入字符串必须开头的部分为合法的数字,而且因为要求输出整型,所以可以将小数点作为不合法的字符,此外还要考虑开头为正负号的情况。例如“-1235.134asdf”, 处理后应变为"-1235"。

如果判断字符串不符合转换整型的条件,则返回0.


得到处理完后的字符串后就要将其转换为数字了,可以通过多项式转换计算整型的值,也可以通过stringstream直接将字符串转为数字,但stringstream的效率可能会比较低一些,但是考虑到整型数本身位数就不多,可以忽略略微的效率问题,而且stringstream的实现也简单得多,更加方便,于是我便采用了stringstream的方法。


class Solution {
public:
    /*判断是否为合法字符*/
    bool isLegal(char c) {
		if (c == '+' || c == '-' || (c >= '0' && c <= '9')) {
			return true;
		}
		return false;
	}
    /*判断是否为数字*/
	bool isNum(char c) {
		if (c >= '0' && c <= '9') {
			return true;
		}
		return false;
	}
    int myAtoi(string str) {
    	string num = "";  // 用于存储过滤后的字符串
    	bool flag = false;
        for (int i = 0; i < str.length(); i++) {
        	if (isspace(str[i]) && flag == false) {  // 利用isspace清除空白
				continue;
			} else {
				flag = true;
			}
        	if (!isLegal(str[i])) {
        		break;
			} else {
				num += str[i];   // 如果字符合法则加入num字符串
			}
		}
		if (!isNum(num[num.length() - 1])) {
			return 0;
		} else {
			stringstream ss;   // 利用stringstream将字符串转换为整型
			ss.str(num);
			int i;
			ss >> i;
			return i;
		}
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值