Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:
class Solution:
def myAtoi(self, s: str) -> int:
if s == "":
return 0
number = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
if s[0] not in number and s[0] != " " and s[0] != "+" and s[0] != "-":
return 0
result = ""
sign = 0
for ch in s:
if sign and ch not in number:
break
elif ch == '+' and result == "":
sign = 1
continue
elif ch == '-' and result == "":
sign = 1
result += '-'
elif ch in number:
result += ch
elif ch == " " and result == "":
continue
else:
break
isnumber = 0
for ch in result:
if ch in number:
isnumber = 1
break
if isnumber == 0:
return 0
intresult = int(result)
if intresult > 2**31-1:
return 2**31 - 1
if intresult < -2**31:
return -2**31
return intresult
s 가 빈 문자열이거나 맨 처음 시작이 word 일 경우 return 0
s 의 문자 하나하나 보면서 result 가 비어있을 때
+
, -
부호 값일 경우는 sign 값을 1 로 설정해준다. -
부호만 result 에 추가함
공백이면 continue
숫자 값이면 result 에 추가해주고 나머지는 break 해준다.
isnumber 로 result 가 숫자 값인지 판별 후, [-2**31, 2**31 - 1]
범위 확인하고 return
끼워 맞추듯이 풀어서 뭔가 지저분하지만.. 그래도 ㄱㅊ은듯
class Solution:
def myAtoi(self, s: str) -> int:
str_list = s.split()
if not str_list:
return 0
num_str = str_list[0]
sign = -1 if num_str[0] == '-' else +1
start = 1 if num_str[0] in '-+' else 0
num = 0
int_boundary = 0x80000000 if sign == -1 else 0x7fffffff # 2147483648 or 2147483647
for i in range(start, len(num_str)):
ord_digit = ord(num_str[i])
if ord_digit < 48 or ord_digit > 57:
break
num *= 10
num += ord_digit - 48
if num >= int_boundary:
num = int_boundary
break
return num * sign
파이썬도 ord()
를 쓰면 아스키코드로 풀기가 가능했다
split()
으로 왼쪽, 오른쪽 공백을 제거해주고 부호를 판별해서 sign 값을 정해준다[-2**31, 2**31 - 1]
범위를 벗어나는지 처리해주고 마지막에 부호를 곱해서 return