[Notes] String

Posted by 西维蜀黍的OJ Blog on 2023-09-10, Last Modified on 2024-02-01

解析

8. String to Integer (atoi)

def myAtoi(self, s: str) -> int:
	s = s.lstrip()
	sign = 1
	if s:
		if s[0] == "+":
			s = s[1:]
		elif s[0] == "-":
			sign = -1
			s = s[1:]

	res = 0
	for c in s:
		if c in "0123456789":
			res = res * 10 + int(c)
		else:
			break
	res *= sign
	return min(2 ** 31 - 1, max(res, -2 ** 31))