字符串转换整数 (atoi)

class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        		if("".equals(str))return 0;
		if (!"+-0123456789".contains(str.charAt(0) + "")) return 0;
		if(str.length()==1 && (str.charAt(0) == '-' || str.charAt(0) == '+' )) return 0;
		
		int mma = -1;

		StringBuffer result = new StringBuffer();
		
		for (int i = 0; i < str.length(); i++) {
			if(mma == -1){
				if("+-0123456789".contains(str.charAt(i) + "")){
					if (str.charAt(i) != '0') {
						result.append(str.charAt(i));
					}
                    mma = 1;
                    if(str.charAt(i) != '+'&&str.charAt(i) != '-' && str.charAt(i) != '0'){
						mma = 2;
					}
                    continue;
				}else{
					break;
				}
			}if(mma == 1){
				if("0123456789".contains(str.charAt(i) + "")){
                    if (str.charAt(i) != '0') {
						result.append(str.charAt(i));
						mma = 2;
					}
                    continue;
				}else{
					break;
				}
			}if(mma == 2){
				if("0123456789".contains(str.charAt(i) + "")){
					result.append(str.charAt(i));
					continue;
				}else{
					break;
				}
			}
			
		}
		int resultNum = 0;

		String result1 = result.toString() ;

		if (result1.length() > 0) {
			if (result1.charAt(0) == '+') {
				result1 = result1.replace("+", "");
			}
		}

		if (result1.length() > 0) {

			String signStrUp = Integer.MAX_VALUE + "";

			String signStrDown = Integer.MIN_VALUE + "";

			int p = result1.length();

			if (result1.charAt(0) == '-') {
				if (p > signStrDown.length()) {
					return Integer.MIN_VALUE;
				} else if (p == signStrDown.length()) {
					if (!compare(result1, signStrDown, 0)) {
						return Integer.MIN_VALUE;
					}
					;
				}
			} else {
				if (p > signStrUp.length()) {
					return Integer.MAX_VALUE;
				} else if (p == signStrUp.length()) {
					if (!compare(result1, signStrUp, 0)) {
						return Integer.MAX_VALUE;
					}
					;
				}
			}

			if ("+".equals(result1) || "-".equals(result1)) {
				return 0;
			}

			resultNum = Integer.parseInt(result1);

		}

		return resultNum;
	}

	private static boolean compare(String c, String z, int i) {

		if (i == z.length()) {
			return true;
		}

		if (c.charAt(i) > z.charAt(i)) {
			return false;
		} else if (c.charAt(i) == z.charAt(i)) {
			int m = i + 1;
			return compare(c, z, m);
		}
		return true;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值