索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
008.String_to_Integer (Easy)
链接:
题目:https://oj.leetcode.com/problems/string-to-integer-atoi/
代码(github):https://github.com/illuz/leetcode
题意:
将一个字符串转化为 int 型。
分析:
注意如果超出范围就返回最接近的 int 数。
如:2147483648 大于 INT_MAX(2147483647) ,就返回 2147483647 。
之前可以用 sscanf 偷懒,最近更新了 case 就被卡了。
要注意几点:
- 跳过前面的空格,\t,\n
- 范围界定
使用 Python 的正则表达式可以很容易处理。
代码:
C++:
class Solution { public: int atoi(string str) { int ret = 0; bool overflow = false; int sign = 1; // default is '+' int i = 0; int len = str.length(); while (i < len && (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')) ++i; if (i == len) return 0; // get sign if (str[i] == '-') { ++i; sign = -1; } else if (str[i] == '+') ++i; while (i < len) { if (!isdigit(str[i])) break; if ((sign == 1 && ret > (INT_MAX - (str[i]-'0')) / 10) || (sign == -1 && -ret < (INT_MIN + (str[i]-'0')) / 10)) { overflow = true; break; } ret = ret * 10 + (str[i] - '0'); ++i; } if (overflow) ret = (sign == 1) ? INT_MAX : INT_MIN; else ret *= sign; return ret; } };
Java:
public class Solution { public int atoi(String str) { int ret = 0; boolean overflow = false; int sign = 1; // default is '+' int i = 0; int len = str.length(); while (i < len && (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t')) ++i; if (i == len) return 0; // get sign if (str.charAt(i) == '-') { ++i; sign = -1; } else if (str.charAt(i) == '+') ++i; while (i < len) { if (str.charAt(i) < '0' || str.charAt(i) > '9') break; if ((sign == 1 && ret > (Integer.MAX_VALUE - (str.charAt(i)-'0')) / 10) || (sign == -1 && -ret < (Integer.MIN_VALUE + (str.charAt(i)-'0')) / 10)) { overflow = true; break; } ret = ret * 10 + (str.charAt(i) - '0'); ++i; } if (overflow) ret = (sign == 1) ? Integer.MAX_VALUE: Integer.MIN_VALUE; else ret *= sign; return ret; } }
Python:
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
使用 Python 的正则表达式:
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
时间: 2024-12-09 12:36:20