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;
			}
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Master_Yoda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值