Tutorialspoint
Problem
Solution
Submissions

String to Integer

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

Write a C program to implement the myAtoi(string) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The function should handle leading whitespaces, optional sign, and convert digits until a non-digit character is encountered or the end of string is reached.

Example 1
  • Input: s = "42"
  • Output: 42
  • Explanation: No leading whitespace. No sign, so positive. Read digits "42". Convert to integer 42.
Example 2
  • Input: s = " -42"
  • Output: -42
  • Explanation: Skip leading whitespaces. Read negative sign. Read digits "42". Apply negative sign to get -42.
Constraints
  • 0 ≤ s.length ≤ 200
  • s consists of English letters, digits, space ' ', '+', and '-'
  • Return 0 if no valid conversion can be performed
  • Clamp the result to 32-bit signed integer range [-2^31, 2^31 - 1]
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsFacebookWalmart
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 all leading whitespace characters
  • Check for optional sign (+ or -)
  • Read digits and build the result number
  • Stop reading when non-digit character is encountered
  • Handle integer overflow by checking before multiplication
  • Return 0 for invalid input or if no digits are found

Steps to solve by this approach:

 Step 1: Initialize index, sign, and result variables
 Step 2: Skip all leading whitespace characters using a loop
 Step 3: Check for optional sign character (+ or -) and update sign variable
 Step 4: Process digits one by one while they are valid
 Step 5: Before adding each digit, check for potential overflow
 Step 6: If overflow occurs, return INT_MAX or INT_MIN based on sign
 Step 7: Apply the sign to final result and return as integer

Submitted Code :