LeetCode OJ - 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.

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.

my answer:

public class Solution_8 {
    public static int myAtoi(String str) {
    	if(str=="")
    		return 0;

    	StringBuilder sb = new StringBuilder();
    	int temp;
    	for(int i=0;i<str.length();i++) {
    		try{
    			temp = Integer.parseInt(str.charAt(i)+"");
    			
    			if(temp ==  ' ' || temp > 9 || temp < 1)
    				continue;
    			else 
    				sb.append(temp);
    			
    		}catch (Exception e){
    			continue;
    		}
    	}

    	String tmp = sb.toString();
    	long num = Long.parseLong(tmp);
    	if (num > Integer.MAX_VALUE)
    		num = Integer.MAX_VALUE;
    	else if (num < Integer.MIN_VALUE)
    		num = Integer.MIN_VALUE;
    	return (int)num;
    }

    public static void main(String[] args){
    	int num = myAtoi("12a4");
    	System.out.println(num);
    }
}

结果是编译通过,但是对于一些情况,ie “    ”会出现运行异常,且没有考虑正负情况。

参考:http://www.2cto.com/kf/201403/285742.html

改进:

import java.math.BigInteger;

public class Solution {
    public static int myAtoi(String str) {
    	if(str==null)
    		return 0;

    	str=str.trim();
    	if(str.length() == 0)
    		return 0;

    	boolean isNeg = false;
    	boolean flag = false;
    	int i=0;
    	int pos = 0;
    	while(i<str.length()){
    		if(str.charAt(i)<='9' && str.charAt(i)>='0')
    			break;
    		if(str.charAt(i) =='-' || str.charAt(i) =='+'){
    			if (str.charAt(i) =='-'){
    				isNeg = true;
    				pos = i;
    				flag = true;
    				break;
    			}
    			if (str.charAt(i) =='+'){
    				pos = i;
    				flag = true;
    				break;	
    			}		
    		}
    		i++;
    	}
    	
    	if (flag)
    		pos=i;

    	StringBuilder sb = new StringBuilder();
    	int temp;
    	for(pos=pos;i<str.length();i++) {
    		try{
    			temp = Integer.parseInt(str.charAt(i)+"");
    			
    			if(temp ==  ' ' || temp > 9 || temp < 0)
    				continue;
    			else 
    				sb.append(temp);
    			
    		}catch (Exception e){
    			continue;
    		}
    	}

    	String tmp = sb.toString();
    	if(tmp.length()==0)
    		return 0;

    	BigInteger num = isNeg? new BigInteger(tmp).negate():new BigInteger(tmp);
    	BigInteger max = BigInteger.valueOf(Integer.MAX_VALUE);
    	BigInteger min = BigInteger.valueOf(Integer.MIN_VALUE);
    	
    	if (num.compareTo(max)>0){
    		num = max;
    	}
    		
    	else if (num.compareTo(min)<0)
    		num = min;
    	return num.intValue();
    }

    public static void main(String[] args){
    	//int num = myAtoi("");
    	//int num = myAtoi("1");
    	//int num = myAtoi("-1");
    	//int num = myAtoi("abc");
    	//int num = myAtoi("-abc");
    	int num = myAtoi("+-2");
    	//int num = myAtoi("9223372036854775808");
    	System.out.println(num);
    }
}

这里真的要吐槽啦~~测试用的9223372036854775808比long还要long,恩,不得已,现学现卖了bigInteger,跟基本数据类型还不太一样,这个大多都是封装的。好不容易把9223372036854775808转换成了Integer.MAX_VALUE,以为 大功就要告成了,谁成想test “+-2”时又是结果不对,我的理解是如果出现多个正负号,取第一个,然后只看后面的数字,所以运行结果是+2,也就是输出2,结果人家要的是0,也许是题目的意思是只能有一个正负号?那么 test “2-5342”的结果又会是啥呢?

呜呜呜,脑筋都快不转了,吃饭去了= = 再想再写的话我选择狗带!

原谅偶的不求甚解...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值