阅读背景:

LeetCode(8 字符串转整数)_暴走的小小菜鸟的博客

来源:互联网 

如题
感觉难点还是就一个越界判断

public static int myAtoi(String str) {
		str = str.trim();//去除头部空格
		int num=0;
		if(str.charAt(0)=='-') {//负号打头
			for(int i=1;i<str.length();i++) {
				char ch = str.charAt(i);
				if(ch>='0'&&ch<='9') {
					if(num<Integer.MIN_VALUE/10||(num==Integer.MIN_VALUE/10&&'0'-ch<Integer.MIN_VALUE%10)) {
						return Integer.MIN_VALUE;//越界判断
					}
					num=num*10-(ch-'0');//注意每一位始终为正
				}else {
					return num;//检索到其他字符提前返回
				}
			}
		}else if(str.charAt(0)=='+') {//正号打头
			for(int i=1;i<str.length();i++) {
				char ch = str.charAt(i);
				if(ch>='0'&&ch<='9') {
					if(num>Integer.MAX_VALUE/10||(num==Integer.MAX_VALUE/10&&ch-'0'>Integer.MAX_VALUE%10)) {
						return Integer.MAX_VALUE;//越界判断
					}
					num=num*10+(ch-'0');
				}else {
					return num;
				}
			}			
		}else if(str.charAt(0)>='0'&&str.charAt(0)<='9') {//数字打头
			num+=(str.charAt(0)-'0');
			for(int i=1;i<str.length();i++) {
				char ch = str.charAt(i);
				if(ch>='0'&&ch<='9') {
					if(num>Integer.MAX_VALUE/10||(num==Integer.MAX_VALUE/10&&ch-'0'>Integer.MAX_VALUE%10)) {
						return Integer.MAX_VALUE;
					}
					num=num*10+(ch-'0');
				}else {
					return num;
				}
			}		
		}else {//其他字符打头
			return 0;
		}
		return num;//对应以数字结尾的输出
	}
public static int myA



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: