String to Integer (atoi) 转换string为整数@LeetCode

148 篇文章 69 订阅
27 篇文章 0 订阅

思路:

处理whitespace和符号位,然后边遍历边累计和



挺tricky的一题,这题我没有用正常的方法来做,用了挺邪恶的方法:

1 用正则表达式过滤掉前面的whitespace

2 用Long去parseLong,这里还遇到奇怪的问题,当parseLong传+号时,在本机跑没问题,一到OJ上就会Runtime Exception!

3 用了Exception做检查


这题肯定有比较正常的做法,但也许这是最直观的方法了


附带几个做Regex比较有用的网站:

http://www.freeformatter.com/java-dotnet-escape.html

http://regexpal.com/

http://www.regexplanet.com/advanced/java/index.html


package Level2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 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.
 * 
 */
public class S8 {

	public static void main(String[] args) {
//		String str = "  sf  -2147483648   asfasdf";
//		String str = "      321f";
//		String str = " -0012a42";
//		String str = " 10522545459";
//		String str = "-abc";
		String str = "+1";
		System.out.println(atoi(str));
	}
	
	public static int atoi(String str) {
		
		if(str==null || str.length()==0){
			return 0;
		}
		
		// 找到第一个非whitespace的
		Pattern p = Pattern.compile( "([\\S]\\d*)" );
		Matcher m = p.matcher(str);
		String trim = str;
		if( m.find() ){
			trim = m.group();
		}
		
		// 判断第一个符号
		char c = trim.charAt(0);
		if(c!='-' && c!='+' && !Character.isDigit(c)){
			return 0;
		}
		// 很奇怪,必须把+号过滤掉,否则OJ返回Runtime Error
		if(c == '+'){
			trim = trim.substring(1);
		}
		
		int ret = 0;
		long temp = 0;
		// tricky,用Long去parse,检查Exception
		try{
			temp = Long.parseLong(trim);
		}catch (Exception e) {
			return 0;
		}
				
        if (temp > Integer.MAX_VALUE){
        	ret = Integer.MAX_VALUE;           
        }
        else if (temp < Integer.MIN_VALUE){
        	ret = Integer.MIN_VALUE;
        }
        else {
        	ret = (int) temp;
        }
		return ret;
    }

}


Second try:

这次是非常正统的做法,肯定挑不出岔。

/*
	 http://www.cnblogs.com/freeneng/archive/2013/04/15/3022107.html
	 Analysis:

Possible input cases:

1. "", empty string

2. "123", simple valid string

3. "+123", valid string with '+' sign

4. "-123", valid string with '-' sign

5. " 123abc ", string with space and other characters

6. "abc123", invalid input string

7. "33333333333333", "-3333333333333", invalid overflow string

According to those given cases, we should follow the steps listed below:

1. check whether the string is empty, define what to return if the string is empty; if it's empty, return directly

2. trim the spaces of the string both at the head and the end

3. judge whether the first character is '+' or '-', by default no either of them are positive num

4. start from the first position, continue convert until meeting the end of the string or a non-numeric character

5. judge whether the result overflows, if overflow, return the MAX_VALUE or MIN_VALUE, else return the result
	 */
	public static int atoi(String str){
		if(str == null || str.length()==0){
			return 0;
		}
		int pos = 0, ret = 0;
		long val = 0L;
		char flag = '+';
		
		str = str.trim();		// 过滤掉前面的whitespace
		if(str.charAt(0)=='+' || str.charAt(0)=='-'){		// 获得符号
			pos++;
			flag = str.charAt(0);
		}
		
		while(pos<str.length() && Character.isDigit(str.charAt(pos))){
			val = val*10 + (str.charAt(pos)-'0');	// 累积和
			pos++;
		}
		
		if(flag == '-'){		// 负号处理
			val = -val;
		}
		
		if(val > Integer.MAX_VALUE){
			ret = Integer.MAX_VALUE;
		}else if(val < Integer.MIN_VALUE){
			ret = Integer.MIN_VALUE;
		}else{
			ret = (int)val;
		}
		return ret;
	}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值