https://leetcode-cn.com/problems/string-to-integer-atoi/submissions/

    1. public class _8_字符串转换整数 {
    2. public int myAtoi(String s) {
    3. if (s == null || s.equals("")) {
    4. return 0;
    5. }
    6. s = removeHeadZero(s.trim());
    7. if (s == null || s.equals("")) {
    8. return 0;
    9. }
    10. char[] str = s.toCharArray();
    11. if (!isValid(str)) {
    12. return 0;
    13. }
    14. // str 是符合日常书写的,正经整数形式
    15. // posi 是否是 非负数
    16. boolean posi = str[0] == '-' ? false : true;
    17. int minq = Integer.MIN_VALUE / 10;
    18. int minr = Integer.MIN_VALUE % 10;
    19. int res = 0;
    20. int cur = 0;
    21. // 先一律转成负数来做, 因为负数比正数多一个
    22. for (int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; i < str.length; i++) {
    23. cur = '0' - str[i];
    24. if ((res < minq) || (res == minq) && cur < minr) {
    25. return posi ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    26. }
    27. res = res * 10 + cur;
    28. }
    29. if (posi && res == Integer.MIN_VALUE) {
    30. return Integer.MAX_VALUE;
    31. }
    32. return posi ? -res : res;
    33. }
    34. private String removeHeadZero(String str) {
    35. boolean r = (str.startsWith("+") || str.startsWith("-"));
    36. int s = r ? 1 : 0;
    37. for (; s < str.length(); s++) {
    38. if (str.charAt(s) != '0') {
    39. break;
    40. }
    41. }
    42. // s 到了第一个不是'0'字符的位置
    43. int e = -1;
    44. // 左<-右
    45. for (int i = str.length() - 1; i >= (r ? 1 : 0); i--) {
    46. if (str.charAt(i) < '0' || str.charAt(i) > '9') {
    47. e = i;
    48. }
    49. }
    50. // e 到了最左的 不是数字字符的位置
    51. return (r ? String.valueOf(str.charAt(0)) : "") + str.substring(s, e == -1 ? str.length() : e);
    52. }
    53. private boolean isValid(char[] chars) {
    54. if (chars[0] != '-' && chars[0] != '+' && (chars[0] < '0' || chars[0] > '9')) {
    55. return false;
    56. }
    57. if ((chars[0] == '-' || chars[0] == '+') && chars.length == 1) {
    58. return false;
    59. }
    60. return true;
    61. }
    62. }
    • 这道题就是细节扣,没什么算法