반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- GitHub Desktop
- C++
- git
- 알고리즘
- 프로콘
- Algorithmus
- 프로그래머스
- baekjoon
- programmers
- 백준
- 자소서
- 리트코드
- 백트래킹
- SRE
- DP
- 격리수준
- 프로콘 갈림현상
- 코딩테스트
- LeetCode
- 제노블레이드 2
- Python
- 알고리즘 종류 정리
- Pro-Con
- python3
- ASF-110
- 네이버 검색 시스템
- 취준
- Ultimate Search
- algorithm
- Github
Archives
- Today
- Total
산타는 없다
[리트코드 / LeetCode] 8. String to Integer (atoi) 풀이 - python3 본문
반응형
문제 원문
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered a whitespace character.Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³¹, 2³¹− 1]. If the numerical value is out of the range of representable values, 2³¹− 1 or −2³¹is returned.
Example 1:
Input: str = "42" Output: 42
Example 2:
Input: str = " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: str = "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: str = "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: str = "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−2³¹) is returned.
Constraints:
0 <= s.length <= 200s consists of English letters (lower-case and upper-case), digits, ' ', '+', '-' and '.'.
코드 원문
class Solution:
def myAtoi(self, s: str) -> int:
풀이
입력받은 문자열에서 숫자를 추출하는 문제입니다. 파이썬으로 작성하였습니다.
입력값에서 앞에 공백을 제외하고 처음 만나는 단어?가 숫자일 때 그 숫자를 파싱 하며 해당 단어 이후의 값은 모두 무시합니다.
주의할 점은 +와 -는 숫자로 취급해야하는 점과 -일 때 결과를 음수로 반환해야 하는 점
마지막으로 -2³¹ ~ 2³¹- 1 범위를 초과하는 값은 초과하는 값에 따라 -2³¹ 또는 2³¹− 1로 반환해야 하는 점입니다.
성공 코드
class Solution:
def myAtoi(self, s: str) -> int:
s.lstrip()
num = 0
Negative = False
pos = 0
for i in s :
if i == ' ' and pos == 0 :
s.lstrip()
continue
elif (i == '+' or i == '-') and pos == 0 :
if i == '-' : Negative = True
if pos == 0 : pos += 1
elif '0' <= i <= '9':
num *= 10
num += int(i)
if pos == 0 : pos += 1
else :
break
if Negative:
num *= -1
if num > 2**31 - 1 : num = 2**31 - 1
elif num < -2**31 : num = -2**31
return num
결과
Runtime: 28 ms, faster than 93.36% of Python3 online submissions for String to Integer (atoi).
Memory Usage: 14.2 MB, less than 44.06% of Python3 online submissions for String to Integer (atoi).
반응형
'코딩테스트 > 리트코드' 카테고리의 다른 글
[리트코드 / LeetCode] 9. Palindrome Number 풀이 - python3 (0) | 2021.01.01 |
---|---|
[리트코드 / LeetCode] 7. Reverse Integer 풀이 - python3 (0) | 2021.01.01 |
[리트코드 / LeetCode] 6. ZigZag Conversion 풀이 - C++ (0) | 2021.01.01 |
[리트코드 / LeetCode] 4. Median of Two Sorted Arrays 풀이 - C++ (0) | 2020.12.30 |
[리트코드 / LeetCode] 3. Longest Substring Without Repeating Characters 풀이 - C++ (0) | 2020.12.30 |
Comments