LeetCode第8题字符串转换成整数

这道题是中等难度的题,确实想了好长时间,因为老是有一些情况没有考虑到,不过最后还是把条件都分清楚了,首先我们需要先把字符串给去掉首尾的空格,其次,还要分为以下几种情况:

  1. 字符串本身就是一个空字符串,应直接返回0
  2. 字符串不是以±以及数字开头的,应直接返回0
  3. 字符串以+开头的,应进行处理
  4. 字符串以-开头应进行处理
  5. 字符串以数字开头应进行处

其中,字符串以正号和负号开头的,还需要考虑一种特殊情况,就是符号后面又是一个符号,比如++2,这种也是不转换的,然后就是安装正常的逻辑,进行转换,需要注意的是转换后的值,可能会溢出,所以我先用的long型的数据来存储,我的答案除了用的内存稍微多一点,其他没有什么问题。

str = str.trim();
		if (str.length() == 0) {
			return 0;
		} else {
			if (str.charAt(0) == '+') {
				if (str.length() == 1) {
					return 0;
				} else {//字符串长度大于等于2时,需要看是否第二个字符是不是数字
					if (str.charAt(1) < 48 || str.charAt(1) > 57) {
						return 0;
					} else {
						byte len = 1;
						long temp = 0;
						while (len < str.length() && str.charAt(len) >= 48 && str.charAt(len) <= 57) {
							temp = temp * 10 + Integer.parseInt(Character.toString(str.charAt(len++)));
							if (temp > Integer.MAX_VALUE) {
								return Integer.MAX_VALUE;
							}
						}
						return (int) temp;

					}

				}

			} else if (str.charAt(0) == '-') {
				if (str.length() == 1) {
					return 0;
				} else {
					if (str.charAt(1) < 48 || str.charAt(1) > 57) {
						return 0;
					} else {
						byte len = 1;
						long temp = 0;
						while (len < str.length() && str.charAt(len) >= 48 && str.charAt(len) <= 57) {
							temp = temp * 10 - Integer.parseInt(Character.toString(str.charAt(len++)));
							if (temp < Integer.MIN_VALUE) {
								return Integer.MIN_VALUE;
							}
						}
						return (int) temp;
					}
				}

			} else if (str.charAt(0) >= 48 && str.charAt(0) <= 57) {
				byte len = 0;
				long temp = 0;
				while (len < str.length() && str.charAt(len) >= 48 && str.charAt(len) <= 57) {
					temp = temp * 10 + Integer.parseInt(Character.toString(str.charAt(len++)));
					if (temp > Integer.MAX_VALUE) {
						return Integer.MAX_VALUE;
					}
				}
				return (int) temp;

			} else {
				return 0;
			}
		}

你可能感兴趣的:(数据结构与算法)