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.
原网址:https://leetcode.com/problems/string-to-integer-atoi/#
看了题干里面的hint之后发现其实要考虑的情况挺多的。算法挺容易实现的,对于可能会出现的一些情况的处理写了好久。
提交的网站不断的报错,一点点的修改之前的算法。
System.out.println( sti.myAtoi("123456789"));
System.out.println( sti.myAtoi("123a456789"));
System.out.println( sti.myAtoi("-123456789"));
System.out.println("xxx");
System.out.println( sti.myAtoi(""));
System.out.println( sti.myAtoi("1321323213123456789"));
System.out.println( sti.myAtoi(" 010"));
System.out.println( sti.myAtoi(" -0012a42"));
System.out.println( sti.myAtoi("-2147483648"));
System.out.println( sti.myAtoi("9223372036854775809"));
1.为空的时候要考虑
2.负数
3.中间若出现非数字,返回之前的部分
4.空格的处理,用trim()
5.int超范围的情况,这里用到的是Long来接受,后来给的用例连Long也超了,再一想不需要。判断当前数字的位数也是可以的。int类型的范围是-2147483648~2147483647
可以通过point 这个计数来判断位数。
6.按题目要求超界限返回-2147483648或2147483647
public class Solution {
public int myAtoi(String str) {
str = str.trim();
if(str.length()==0)
return 0 ;
int len = str.length();
// 先判断第一位
boolean isDigit = false;
boolean isNegative = false;
long res = 0;
if (str.charAt(0) >= '0' && str.charAt(0) <= '9') {
isDigit = true;
res = Integer.parseInt(str.charAt(0) + "");
}
if (str.charAt(0) == '-') {
isDigit = true;
isNegative = true;
}
if (str.charAt(0) == '+') {
isDigit = true;
isNegative = false;
}
if (!isDigit) {
return 0;
}
// 如果后面再出现非数字也是直接结束,用long型来接受,一旦越界立即结束。 如果是负数则最后取反即可
int point = 1;
while (point < len && point <12) {
if(point>11)
{
if(isNegative)
return -2147483648;
else
return 2147483647;
}
if (str.charAt(point) < '0' || str.charAt(point) > '9') {
// 之前的内容如果合法就输出
if(isNegative)
res=-res;
if (res > 2147483647)
return 2147483647;
if(res< -2147483648)
return -2147483648;
return (int) res;
}
res = res * 10 + Integer.parseInt(str.charAt(point) + "");
point++;
}
if(isNegative)
res=-res;
if (res > 2147483647)
return 2147483647;
if(res< -2147483648)
return -2147483648;
return (int)res;
}
}