实现atoi函数(string转integer)

实现atoi函数(string转integer)

String to Integer (atoi)
  • Implement atoi to convert a string to an integer.
  • Hint: Carefully consider all 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..

  • Example 1:

Input: ""
Output: 0
  • Example 2:
Input: "+2"
Output: 2
  • Example 3:
Input: "+-2"
Output: 0
  • Example 4:
Input: "+"
Output: 0
  • Example 5:
Input: "-223pasudasd"
Output: -223

思路

  1. 利用Python内置的int(str)函数可以将字符串快速转换成int型
  2. 利用int(str)是否抛出异常来快速判断str能否被转换成int,进而迅速确定输入字符串中第一个非数字字符的位置
  3. 需要注意处理+,-符号的问题

代码

class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip()
        retstr = ''
        try:
            for _, item in enumerate(s):
                if item == '+' or item == '-':
                    retstr += item
                else:
                    retstr += str(int(item))
        finally:
            if len(retstr) == 0:
                return 0
            else:
                try:
                    # 如果 retstr 是 '-' 或者 '+',len(retstr) != 0 但是会抛出异常,此时返回0
                    # 由于python的int没有取值上限,如果规定int为32位,需要判断int(retstr)是否大于2147483647或者小余-2147483648
                    return int(retstr)
                except:
                    return 0

本题以及其它leetcode题目代码github地址: github地址

### 实现一个类似于 `atoi` 的字符串整数函数实现类似于 `atoi` 的函数时,需要考虑以下几个关键点: 1. **跳过前导空格**:字符串的起始部分可能包含多个空格,这些空格应该被忽略。 2. **处理符号**:字符串的起始部分可能包含正号 `+` 或负号 `-`,用于表示结果的符号。 3. **读取数字**:从字符串中读取连续的数字字符,并将其换为整数。 4. **溢出处理**:在换过程中,如果整数超出 `int` 类型的范围(即 $[-2^{31}, 2^{31}-1]$),需要进行截断处理。 5. **非法字符处理**:如果遇到非数字字符,换应立即停止。 以下是一个完整的实现示例(使用 Java): ```java public class MyAtoi { public static int myAtoi(String str) { if (str == null || str.trim().length() == 0) { return 0; } str = str.trim(); // 去除前导和尾随空格 int i = 0; int sign = 1; // 用于记录正负号 long result = 0; // 使用 long 来防止溢出 // 处理符号 if (str.charAt(i) == '+' || str.charAt(i) == '-') { sign = (str.charAt(i) == '-') ? -1 : 1; i++; } // 读取数字 while (i < str.length() && Character.isDigit(str.charAt(i))) { result = result * 10 + (str.charAt(i) - '0'); // 检查是否溢出 if (sign * result > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (sign * result < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } i++; } return (int) (sign * result); } public static void main(String[] args) { System.out.println(myAtoi("42")); // 输出 42 System.out.println(myAtoi(" -42")); // 输出 -42 System.out.println(myAtoi("4193 with words")); // 输出 4193 System.out.println(myAtoi("words and 987")); // 输出 0 System.out.println(myAtoi("-91283472332")); // 输出 -2147483648 (溢出) } } ``` #### 代码说明: - **去除空格**:使用 `trim()` 方法去掉字符串的前后空格。 - **符号处理**:检查字符串的起始字符是否为 `+` 或 `-`,并设置符号。 - **数字读取**:使用 `while` 循环逐个读取数字字符,并通过 `result = result * 10 + (str.charAt(i) - '0')` 将其换为整数。 - **溢出检查**:在每一步计算后检查是否超出 `int` 的范围,如果超出则返回相应的边界值(`Integer.MAX_VALUE` 或 `Integer.MIN_VALUE`)。 ### 示例运行结果 - 输入 `"42"`,输出 `42` - 输入 `" -42"`,输出 `-42` - 输入 `"4193 with words"`,输出 `4193` - 输入 `"words and 987"`,输出 `0` - 输入 `"-91283472332"`,输出 `-2147483648`(溢出) ### 注意事项 - **非法字符**:遇到非数字字符时,换过程立即停止。 - **边界处理**:当换后的数值超出 `int` 范围时,返回相应的最大值或最小值。 - **空字符串**:如果字符串为空或仅包含空格,则返回 `0`。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值