LeetCode 8: String to Integer (atoi) – Python & JavaScript Solutions Explained

LeetCode 8: String to Integer (atoi) - Python & JavaScript Solutions

String to Integer (atoi) - LeetCode Problem 8

Difficulty: Medium

Problem Statement

Implement the atoi function, which converts a string into an integer.

Approach & Explanation

  • Remove leading whitespace.
  • Check for a sign (+ or -).
  • Extract numerical digits.
  • Clamp to 32-bit integer limits.

Python Solution:


import re
def myAtoi(s: str) -> int:
    match = re.match(r'^[\+\-]?\d+', s.lstrip())
    if not match:
        return 0
    num = int(match.group())
    return max(min(num, 2**31 - 1), -2**31)
    

JavaScript Solution:


function myAtoi(s) {
    let num = parseInt(s.trim(), 10);
    if (isNaN(num)) return 0;
    return Math.max(Math.min(num, 2**31 - 1), -(2**31));
}
    

Time Complexity

O(n) because we parse each character.

Comments

Popular posts from this blog

LeetCode Problem #10: Regular Expression Matching - Explanation and Solutions in Python and JavaScript

LeetCode Problem #1: Two Sum - Explanation and Solutions in Python and JavaScript

LeetCode Problem #2: Add Two Numbers - Explanation and Solutions in Python and JavaScript