Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

eumjo_o

leetcode 0008 - String to Integer (atoi) / Medium / Typescript 본문

카테고리 없음

leetcode 0008 - String to Integer (atoi) / Medium / Typescript

eumjo_o 2023. 3. 31. 21:05

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;
};