设为首页 加入收藏

TOP

LeetCode-String to Integer (atoi)
2015-07-20 17:43:01 来源: 作者: 【 】 浏览:1
Tags:LeetCode-String 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.

分析,本题注意点:

1) 空字符串

2) 正负号

3) 非法字符

4)越界,应返回最大值、最小值

源码Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)

?

public class Solution {
	public int atoi(String str) {
		int i = 0;
		if (str.length() == 0) {
			return 0;
		}
		while (i < str.length() && str.charAt(i) == ' ') {
			i++;
		}
		int sign = 1;
		if (str.charAt(i) == '+') {
			i++;
		} else if (str.charAt(i) == '-') {
			i++;
			sign = -1;
		}

		int number = 0;
		while (i < str.length()) {
			if (str.charAt(i) < '0' || str.charAt(i) > '9') { //illegal
				return sign * number;
			}
			if (Integer.MAX_VALUE / 10 < number
					|| (Integer.MAX_VALUE / 10 == number 
					    && (str.charAt(i) - '0') > Integer.MAX_VALUE % 10)) {
				return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
			}
			number = 10 * number + str.charAt(i) - '0';
			i++;
		}
		return sign * number;
	}
}

?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇NSAssert NSCAssert NSParameterA.. 下一篇ZOJ 3814 Sawtooth Puzzle(牡丹..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C++中智能指针的性能 (2025-12-25 03:49:29)
·如何用智能指针实现c (2025-12-25 03:49:27)
·如何在 C 语言中管理 (2025-12-25 03:20:14)
·C语言和内存管理有什 (2025-12-25 03:20:11)
·为什么C语言从不被淘 (2025-12-25 03:20:08)