友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

8. String to Integer (atoi)

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-231, 231- 1]. If the numerical value is out of the range of representable values, INT_MAX (231- 1) or INT_MIN (-231) is returned.

Example 1:
Input: "42"
Output: 42
Example 2:
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (-231) is returned.

解题分析

result > (Integer.MAX_VALUE - num) / 10 注意这个判断移除方法。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2019-07-14 19:57
 */
public int myAtoi(String str) {
  char[] chars = str.toCharArray();
  int n = str.length();
  int idx = 0;
  // 除去前面的空白符
  while (idx < n && Character.isWhitespace(chars[idx])) {
    idx++;
  }
  if (idx == n) {
    return 0;
  }
  // 判断正负号
  boolean negative = false;
  if (chars[idx] == '-') {
    negative = true;
    idx++;
  } else if (chars[idx] == '+') {
    // negative = false;
    idx++;
  } else if (!Character.isDigit(chars[idx])) {
    return 0;
  }
  // 计算数字
  int result = 0;
  while (idx < n && Character.isDigit(chars[idx])) {
    int num = chars[idx] - '0';
    // 注意这个判断是否溢出的方式。
    if (result > (Integer.MAX_VALUE - num) / 10) {
      return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    }
    result = result * 10 + num;
    idx++;
  }
  return negative ? -result : result;
}

/**
 * Runtime: 1 ms, faster than 100.00% of Java online submissions for String to Integer (atoi).
 *
 * Memory Usage: 35.8 MB, less than 99.90% of Java online submissions for String to Integer (atoi).
 */
public int myAtoi2(String str) {
  int result = 0;
  if (Objects.isNull(str) || str.length() == 0) {
    return result;
  }

  int index = 0;
  int length = str.length();
  while (index < length && str.charAt(index) == ' ') {
    index++;
  }

  int sign = 1;
  if (index < length && isSign(str.charAt(index))) {
    if (str.charAt(index) == '-') {
      sign = -1;
    }
    index++;
  }

  int decimals = 10;
  while (index < length && isNumber(str.charAt(index))) {
    int number = str.charAt(index) - '0';

    if (result > Integer.MAX_VALUE / 10
      || (result == Integer.MAX_VALUE / 10 && number > Integer.MAX_VALUE % 10)) {
      return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    }

    result = result * decimals + number;

    index++;
  }

  return result * sign;
}

private boolean isNumber(char aChar) {
  return '0' <= aChar && aChar <= '9';
}

private boolean isSign(char aChar) {
  return aChar == '-' || aChar == '+';
}

public int myAtoiD2u(String str) {
  long result = 0;
  if (Objects.isNull(str) || str.length() == 0) {
    return (int) result;
  }
  char[] chars = str.toCharArray();
  int start = -1;
  int end = -1;
  int signed = 1;
  boolean hasSigned = false;
  boolean isStarted = false;
  boolean firstIsZero = true;
  for (int i = 0; i < chars.length; i++) {
    char aChar = chars[i];
    if (isStarted && !isNumber(aChar)) {
      break;
    }
    if (aChar == ' ') {
      start++;
      continue;
    }
    if (!isNumber(aChar) && !isSign(aChar)) {
      return (int) result;
    }
    if (isSign(aChar) && !hasSigned) {
      if (aChar == '-') {
        signed = -1;
      }
      hasSigned = true;
      isStarted = true;
      continue;
    }
    isStarted = true;
    if (firstIsZero && aChar == '0') {
      continue;
    }
    if (isStarted && !isNumber(aChar)) {
      break;
    }
    if (firstIsZero && aChar != '0' && isNumber(aChar)) {
      firstIsZero = false;
      start = i;
      end = i;
    }
    if (isNumber(aChar)) {
      end = i;
    } else {
      break;
    }
  }

  for (int i = end; chars.length > i && i >= start && start >= 0; i--) {
    char aChar = chars[i];
    long base = pow(10, end - i);
    if (base > Integer.MAX_VALUE) {
      if (signed == 1) {
        return Integer.MAX_VALUE;
      } else {
        return Integer.MIN_VALUE;
      }
    }
    if ('0' == aChar || isSign(aChar)) {
      continue;
    }
    if (!isNumber(aChar)) {
      break;
    }
    long newResult = (long) (aChar - '0') * base + result;
    boolean isOutOfRange = (signed > 0 && newResult > Integer.MAX_VALUE)
      || (signed < 0 && newResult * signed < Integer.MIN_VALUE);
    if (isOutOfRange) {
      if (signed == 1) {
        return Integer.MAX_VALUE;
      } else {
        return Integer.MIN_VALUE;
      }
    }
    result = newResult;
  }

  result *= signed;

  return (int) result;
}

private long pow(int base, int exponent) {
  long result = 1L;
  for (int i = 0; i < exponent; i++) {
    result *= base;
  }
  return result;
}