8. String to Integer [M] to Integer String

topic

Inplement atoi which converts a string to an integer.
Note:

  • Consider the space character ' ' as a whitespace character.
  • The first non-whitespace character must be a numerical digit or a +/- sign.
  • Assume the environment can only store integer within 32-bit signed range:\([-2^{31}, \; 2^{31}-1]\)

    C ++ ideas

    The key problem is that various conditions must be met:
  • Leading spaces
  • Processing the sign of
  • Overflow judgment
  • Digital processing

int myAtoi(string str){
  int p = 0, flag = 1;
  while(str[p] == ' '){  //空格的处理
    p++;
  }
  if(str[p] == '+'){  //正负号的处理
    p++;
  }
  else if(str[p] == '-'){
    flag = -1;
    p++;
  }
  long resInt = 0;
  for(int i = p; i < str.size(); i++){
    if(str[i] < '0' || str[i] > '9') break;
    int temp = str[i] - '0'; //将字符转化为数字
    resInt = 10 * resInt + temp;
    if(flag == 1){  //溢出判断
      if(resInt > INT_MAX)  return INT_MAX;
    }
    else{
      if(resInt - 1 > INT_MAX)  return INT_MIN;  //除去符号,INT_MAX与INT_MIN只相差1
    }
  }
  resInt = sign * resInt;
  return resInt;
}

Python ideas

  • str.strip (rm) deleted at the beginning and end of str character, inside a character sequence rm
  • str.lstrip (rm) to delete the character at the beginning of str, located character sequence rm
  • str.rstrip (rm) to delete the character at the end of str, located character sequence rm
  • Using a try-except block to check the abnormal input
  • Regular expressions, re module
    \ d represents [0,9] numbers, \ d + represent more than one digit
    ^ represents the beginning of the match string
    -? Represents a character or subexpression 0 or 1 before repeating matching
    re.search first scan the entire string and returns a successful match, the match is successful returns an object matching, otherwise None
    Group () is to use packet () regular expression enclosed, showing the contents of a packet matched. group () outputs a tuple of the corresponding group.
def myAtoi(self, str):
  str = str.lstrip();
  try:
    res = int(re.search('^[\+\-] ? \d+', str).group());
  except:
    res = 0;
  return min(max(-2147483648, res), 2147483647)

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993437.html