eumjo_o
leetcode 0008 - String to Integer (atoi) / Medium / Typescript 본문
https://leetcode.com/problems/string-to-integer-atoi/
String to Integer (atoi) - LeetCode
Can you solve this real interview question? String to Integer (atoi) - 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: 1. Read
leetcode.com
Time Complexity O(N), Space Complexity O(1)
- Number.parseInt 는 문자열을 순회하며 숫자를 찾기 때문에 문자열 길이 만큼의 시간 소요
- MAXINT, MININT 인 경우 조건, 숫자가 없는 문자인 경우 0을 return 하도록 구현
Javascript의 parseInt가 위에서 요구하는 것들을 다 해주는 함수.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN
1. If the input string, with leading whitespace and possible +/- signs removed, begins with 0x or 0X (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexadecimal number.
2. If the input string begins with any other value, the radix is 10 (decimal)
function myAtoi(s: string): number {
const num = Number.parseInt(s);
if(num < -2147483648) return -2147483648;
if(num > 2147483647) return 2147483647;
return num || 0;
};