leetCode 8. String to Integer (atoi)

    题目连接:https://leetcode.com/problems/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.

    题意分析:题目很简单,就是把string类型转化为一个int类型。我自己提交的答案ac之后,查看一下讨论区其他人的解法,大家的思路都差不多,这道题的难度分在easy,但是通过率却很低,很大原因就是不断有各种test case通不过,很考验细节(深有体会啊,一堆红色wa~)。对于这些oj系统,还是有人说得好“难度大的题重在巧妙和思维,越是简单的题越是重细节”。这里的细节包括但不限于:

    1)输入为空

    2)边界问题

    3)特殊符号

    含泪贴上自己AC的低质量代码,讨论区也有很多人直接用写好的API,或者考虑边界时候使用long类型,还有使用python的正则表达式都有。

public static int myAtoi(String str) {
		int res = 0;
		// whether res is positive or not
		boolean positive = true;
		// the num of char before digit
		int sigCount = 0;
		// ignore the space before or afer the string
		String fixStr = str.trim();
		if(!fixStr.isEmpty()) {
			int len = fixStr.length();
			int idx;
			// judge the res is positive or not, and if the char before res is not '+' nor '-', return 0
			for(idx = 0; idx < len; idx++) {
				char ch = fixStr.charAt(idx);
				if(ch >= '0' && ch <= '9') {
					// begin with digits
					break;
				} else {
					// too many sign or char isn't '+' or '-', e.g. '++-2133', ' b23351'
					if(++sigCount > 1 || (ch!='+' && ch!='-'))
						return 0;
					else if(ch == '-')
						positive = false;
				}
			}
			for(; idx < len; idx++) {
				char ch = fixStr.charAt(idx);
				if(ch >= '0' && ch <= '9') {
					// equalsTo "res*10+(ch-'0') > Integer.MAX_VALUE", which is overflow
					if(positive && res > (Integer.MAX_VALUE - (ch-'0'))/10)
						return Integer.MAX_VALUE;
					// equalsTo "-(res*10+(ch-'0')) < Integer.MIN_VALUE", which is overflow
					else if(!positive && res > -((Integer.MIN_VALUE + (ch-'0'))/10))
						return Integer.MIN_VALUE;
					else 
						res = res*10 + (ch - '0');
				} else
					// if the test case is '233f54' for example, output will be '233'
					break;
			}
		}
		return positive?res:-res;
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值