8. String to Integer
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
将一个字符串转化为 int 型。
1. null or empty string 2. white spaces 3. +/- sign 4. calculate real value 5. handle min & max
public int atoi(String str) { if (str == null || str.length() < 1) return 0; // trim white spaces str = str.trim(); char flag = '+'; // check negative or positive int i = 0; if (str.charAt(0) == '-') { flag = '-'; i++; } else if (str.charAt(0) == '+') { i++; } // use double to store result double result = 0; // calculate value while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { result = result * 10 + (str.charAt(i) - '0'); i++; } if (flag == '-') result = -result; // handle max and min if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int) result; }
class Solution: # @return an integer def atoi(self, str): str = str.strip() if not str: return 0 MAX_INT = 2147483647 MIN_INT = -2147483648 ret = 0 overflow = False pos = 0 sign = 1 if str[pos] == '-': pos += 1 sign = -1 elif str[pos] == '+': pos += 1 for i in range(pos, len(str)): if not str[i].isdigit(): break ret = ret * 10 + int(str[i]) if not MIN_INT <= sign * ret <= MAX_INT: overflow = True break if overflow: return MAX_INT if sign == 1 else MIN_INT else: return sign * ret
# 正则表达式 class Solution: # @return an integer def atoi(self, str): str = str.strip() str = re.match(r'^[+-]?\d+', str).group() MAX_INT = 2147483647 MIN_INT = -2147483648 try: ret = int(str) if ret > MAX_INT: return MAX_INT elif ret < MIN_INT: return MIN_INT else: return ret except: return 0