Title description
Implement the function atoi. The function of the function is to convert a string to an integer
Tip: Think carefully about all possible input situations. This question does not give input restrictions, you need to consider all possible situations yourself.
Example 1
enter
"123"
return value
123
Code implementation :
import java.util.*;
public class Solution {
/**
*
* @param str string字符串
* @return int整型
*/
public int atoi (String str) {
if (str == null && str.equals("")) {
return 0;
}
boolean flag = true;
str = str.trim();
char[] arr = str.toCharArray();
long result = 0;
for (char num : arr) {
if (num == '+') {
continue;
} else if (num == '-') {
flag = false;
continue;
} else if (result == 0 && num == '0') {
continue;
} else if (num < '0' || num > '9') {
break;
}
result = result * 10 + (num - '0');
}
if (!flag) {
result *= -1;
}
if (result >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)result;
}
}