猿问

新手关于leetcode 8的问题,charAt()的问题,已经卡了一晚上了 求解

目的是实现将string转换成integer,如果输入+99,则输出为99,;如果输入-99,则输出为-99,且考虑溢出。
public class Solution {

我的代码如上图,为什么我输入+1100这种格式的数字后,输出仍旧是0?小弟新手刷lc,这道题已经卡了一晚上了,求解

慕娘9325324
浏览 1144回答 1
1回答

忽然笑

for (int i = 0; i < newstr.length(); i++)应该改成for (int i = 1; i < newstr.length(); i++), 因为按照你的描述,下标为0的字符应该是+或者-。public class Solution {&nbsp; &nbsp; public int atoi(String str) {&nbsp; &nbsp; &nbsp; &nbsp; if (str == null || str.length() <= 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; &nbsp; long rs = 0;&nbsp; &nbsp; &nbsp; &nbsp; char[] chArr = str.trim().toCharArray();&nbsp; &nbsp; &nbsp; &nbsp; boolean isPositive = chArr[0] == '+' || Character.isDigit(chArr[0]);&nbsp; &nbsp; &nbsp; &nbsp; int start = Character.isDigit(chArr[0]) ? 0 : 1;&nbsp; &nbsp; &nbsp; &nbsp; for (; start < chArr.length; start++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Character.isDigit(chArr[start]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rs = rs * 10 + (chArr[start] - '0');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; rs = isPositive ? rs : -rs;&nbsp; &nbsp; &nbsp; &nbsp; if (isPositive)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rs > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rs;&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rs < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) rs;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(new Solution().atoi("-1100"));&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答