8. String to Integer[M]字符串转整数

题目

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++思路

    问题的关键在于必须满足各种条件:
  • 开头的空格
  • 正负号的处理
  • 溢出判断
  • 数字的处理

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思路

  • str.strip(rm) 删除str字符中开头和结尾处,位于rm序列的字符
  • str.lstrip(rm) 删除str字符中开头处,位于rm序列的字符
  • str.rstrip(rm) 删除str字符中结尾处,位于rm序列的字符
  • 利用try-except块来检查异常输入
  • 正则表达式,re模块
    \d 表示[0,9]的数字,\d+ 表示不止一个数字
    ^ 表示匹配字符串的开头
    -?表示匹配前一个字符或子表达式0次或1次重复
    re.search 扫描整个字符串并返回第一个成功的匹配,匹配成功返回一个匹配的对象,否则返回None
    group() 分组就是用()括起来的正则表达式,匹配出的内容表示一个分组。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)

猜你喜欢

转载自www.cnblogs.com/Jessey-Ge/p/10993437.html