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.
这道题我觉得挺无趣的,可能是因为OJ题目做的太少,不太清楚各种规则,有些想当然,没有完全理解清楚题意就开始写代码以至于浪费了很长时间。不过有意思的是,当我提交成功之后,系统提示我解锁了一个solution,看了一下官方给的solution,瞬间明白了,好的算法和烂算法的差别。Although I make it possible, I make it ugly。
以下是我冗长的Python代码:
ef atoi(strg):
illeFigure = False
fFigure = False
figure = []
numList = []
num = []
for i in range(0, 10):
numList.append(str(i))
for i in range(0, len(strg)):
if illeFigure == False:
if strg[i] == " ":
continue
elif strg[i] == "+" or strg[i] == "-":
illeFigure = True
fFigure = True
figure.append(strg[i])
continue
elif strg[i] in numList:
num.append(strg[i])
illeFigure = True
continue
else:
break
if illeFigure == True:
if strg[i] in numList:
num.append(strg[i])
continue
else:
break
if illeFigure == False:
return 0
else:
if len(num) == 0:
return 0
d = ''.join(num)
y = re.findall("[1-9][0-9]*", d)
if len(y) == 0:
return 0
x = ''.join(y)
print("x is:" + x)
if fFigure == True:
if figure[0] == "+":
if len(x) == 10 and x >= "2147483647":
return 2147483647
elif len(x) > 10:
return 2147483647
else:
return int(x)
if figure[0] == "-":
if len(x) == 10 and x >= "2147483648":
return -2147483648
elif len(x) > 10:
return -2147483648
else:
return int(-int(x))
if len(x) == 10 and x > "2147483647":
return 2147483647
elif len(x) > 10:
return 2147483647
else:
return int(x)
官方高大上的solution:
To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int atoi(String str) {
int n = str.length();
int i = 0;
while (i < n && Character.isWhitespace(str.charAt(i))) i++;
int sign = 1;
if (i < n && str.charAt(i) == '+') {
i++;
} else if (i < n && str.charAt(i) == '-') {
sign = -1;
i++;
}
int num = 0;
while (i < n && Character.isDigit(str.charAt(i))) {
int digit = Character.getNumericValue(str.charAt(i));
if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}
作者分享了自己在解决复杂编程问题时的挑战与思考过程,从最初的盲目尝试到最终通过优化算法实现目标,文章详细阐述了遇到的问题、采取的策略以及最终成功的方法。通过对比自己冗长且低效的代码与官方简洁高效的解决方案,作者反思了代码质量和效率的重要性。此篇博客不仅提供了解决实际编程问题的实例,还强调了在面对复杂任务时保持耐心、深入理解需求和不断优化的重要性。
995

被折叠的 条评论
为什么被折叠?



