码迷,mamicode.com
首页 > 其他好文 > 详细

atoi

时间:2015-03-16 16:24:05      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

	public int atoi(String str) {
		int f = 1;
		int result = 0;
		boolean start = false;
		for (int i = 0; i < str.length(); ++i) {
			if (start) {
				if (str.charAt(i) < '0' || str.charAt(i) > '9') {
					break;
				} else {
					if (f == 1 && result >= Integer.MAX_VALUE / 10) {
						if (result > Integer.MAX_VALUE / 10
								|| (str.charAt(i) - '0') > Integer.MAX_VALUE % 10) {
							return Integer.MAX_VALUE;
						}
					} else if (f == -1 && f * result <= Integer.MIN_VALUE / 10) {
						if (f * result < Integer.MIN_VALUE / 10
								|| (str.charAt(i) - '0') > (0 - (Integer.MIN_VALUE % 10))) {
							return Integer.MIN_VALUE;
						}
					}
					result = result * 10 + (str.charAt(i) - '0');
				}
			} else {
				if (str.charAt(i) == ' ') {
					continue;
				} else if (str.charAt(i) == '-') {
					f = -1;
				} else if (str.charAt(i) == '+') {
					f = 1;
				} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
					result = str.charAt(i) - '0';
				} else {
				    break;
				}
				start=true;
			}
		}
		return f * result;

	}
}


atoi

标签:

原文地址:http://blog.csdn.net/youdianmengxiangba/article/details/44307417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!