Tutorialspoint
Problem
Solution
Submissions

String to Integer

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to implement the string-to-integer conversion function (similar to C's atoi function). The function should convert a string to a 32-bit signed integer, handling whitespace, optional signs, and invalid characters while respecting integer overflow limits.

Example 1
  • Input: s = "42"
  • Output: 42
  • Explanation:
    • The string "42" contains only valid digits.
    • No leading whitespace or sign to handle.
    • Parse digits 4 and 2 to form number 42.
    • 42 is within 32-bit integer range. Return 42.
Example 2
  • Input: s = " -42"
  • Output: -42
  • Explanation:
    • The string " -42" starts with whitespace.
    • Skip leading whitespace to get "-42".
    • Detect negative sign and parse digits 4, 2.
    • Form number -42 which is within valid range.
    • Return -42.
Constraints
  • 0 ≤ s.length ≤ 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'
  • Handle integer overflow by clamping to [-2³¹, 2³¹ - 1]
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsNumberPwCPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Skip leading whitespace characters first
  • Check for optional sign (+ or -) and store the sign
  • Parse digits one by one until non-digit character is encountered
  • Handle integer overflow by checking bounds before multiplication
  • Return 0 if no valid conversion can be performed
  • Clamp result to 32-bit signed integer range

Steps to solve by this approach:

 Step 1: Initialize variables for index, sign, result, and integer bounds.
 Step 2: Skip all leading whitespace characters in the string.
 Step 3: Check for optional '+' or '-' sign and update sign variable accordingly.
 Step 4: Parse digits one by one while they are valid numeric characters.
 Step 5: Before adding each digit, check for potential integer overflow.
 Step 6: If overflow detected, return appropriate boundary value (INT_MAX or INT_MIN).
 Step 7: Apply the sign to the final result and return the converted integer.

Submitted Code :