跳至主要內容

LeetCode刷题第8题:字符串转换整数 (atoi)

weh-coder(小魏)2024年11月3日算法leetcode算法leetcode中等约 758 字大约 3 分钟

原文链接https://leetcode.cn/problems/string-to-integer-atoi/description/

题意

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。

函数 myAtoi(string s) 的算法如下:

返回整数作为最终结果。

示例

示例 1:

输入:s = "42"
输出:42
解释:加粗的字符串为已经读入的字符,插入符号是当前读取的字符。
带下划线线的字符是所读的内容,插入符号是当前读入位置。
第 1 步:"42"(当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"42"(读入 "42")
           ^

示例 2:

输入:s = " -042"
输出:-42
解释:
第 1 步:"   -042"(读入前导空格,但忽视掉)
            ^
第 2 步:"   -042"(读入 '-' 字符,所以结果应该是负数)
             ^
第 3 步:"   -042"(读入 "042",在结果中忽略前导零)
               ^

示例 3:

输入:s = "1337c0d3"
输出:1337
解释:
第 1 步:"1337c0d3"(当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"1337c0d3"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"1337c0d3"(读入 "1337";由于下一个字符不是一个数字,所以读入停止)
             ^

示例 4:

输入:s = "0-1"
输出:0
解释:
第 1 步:"0-1" (当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"0-1" (当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"0-1" (读入 "0";由于下一个字符不是一个数字,所以读入停止)
          ^

示例 5:

输入:s = "words and 987"
输出:0
解释:
读取在第一个非数字字符“w”处停止。

解题

class Solution {
    public int myAtoi(String s) {
        char[] ch = s.trim().toCharArray();
        if (ch.length == 0) return 0;
        int res = 0;
        int flag = 1;
        int start = 1;
        int bd = Integer.MAX_VALUE/10;
        if(ch[0]=='-') flag=-1;
        else if(ch[0]!='+') start=0;
        for(int i=start;i<ch.length;i++){
            if(ch[i] <'0' ||ch[i]>'9') break;
            if(res>bd ||res==bd &&ch[i]>'7') return flag==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
            res = res*10+(ch[i]-'0');
        }
        return res*flag;
    }
}