LeetCode 8. 字符串转换整数 (atoi)

题目描述

🔥 8. 字符串转换整数 (atoi)

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func myAtoi(s string) int {
	s = strings.TrimSpace(s)
	if s == "" {
		return 0
	}

	sign := 1
	if s[0] == '-' {
		sign = -1
		s = s[1:]
	} else if s[0] == '+' {
		s = s[1:]
	}

	num := 0
	for _, c := range s {
		if c < '0' || c > '9' {
			break
		}
		num = num*10 + int(c-'0')
		if num*sign > math.MaxInt32 {
			return math.MaxInt32
		} else if num*sign < math.MinInt32 {
			return math.MinInt32
		}
	}
	return num * sign
}

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        s = s.trim();
        int sign = 1;
        long res = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i == 0 && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
                if (s.charAt(i) == '-') {
                    sign = -1;
                }
            } else if (Character.isDigit(s.charAt(i))) {
                res = res * 10 + (s.charAt(i) - '0');
                if (sign * res > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                } else if (sign * res < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            } else {
                break;
            }
        }
        return (int) (sign * res);
    }
}

相似题目

题目 难度 题解
整数反转 Medium  
有效数字 Hard  
本文作者:
本文链接: https://hgnulb.github.io/blog/71927843
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!