Algorithm-String to Integer (Ato

2019-04-13  本文已影响0人  cctoken

Algorithm String to Integer

Description

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

Example1

Example2

Example 3

Example 4

Example 5

Submission

public class Atoi {
  public int myAtoi(String str) {
    str = str.trim();
    if (str.length() == 0) {
      return 0;
    }
    int index = 0;
    int res = 0;
    boolean negative = false;

    if (str.charAt(0) == '-') {
      negative = true;
      index ++;
    } else if (str.charAt(0) == '+') {
      negative = false;
      index ++;
    }
    while (index < str.length()) {
      if (isDigit(str.charAt(index))) {
        int val = str.charAt(index) - '0';
        // detect over-flow
        if (res > (Integer.MAX_VALUE - val) / 10) {
          return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
        res = res * 10 + val;
      } else {
        break;
      }
      index ++;
    }
    return negative ? -res : res;

  }

  private static boolean isDigit(char s) {
    if (s < '0' || s > '9') {
      return false;
    }
    return true;
  }
}

Solution

将给定的字符串转换为数字类型,但是根据描述规定,有几个特殊的地方需要注意

从左到右遍历,进行trim处理,空格忽略掉

遇见非 whitespace的char时,如果不满足数字的要求,即,既非数字也不是+ - 符号,此时直接返回 0

截掉字符串序列 在数字后非数字的字符,只对有效字符进行解析

代码逻辑是

对遇到的第一个非空格字符进行判断,用以标记数字的正负值,默认为正

根据index递增继续遍历,基于 res = res * 10 + value, 其中 value为当前遍历到的字符对应的十进制数值

需要注意的是,必须判断是否会发生溢出,即要求 res * 10 + value < Integer.MAX_VALUE,所以我们先判断 res 是否是 res > (Integer.MAX_VALUE) - value / 10,如果即将溢出,直接返回对应正负值的最大最小值

Submission Result

image.png
上一篇 下一篇

猜你喜欢

热点阅读