coding-interview|August 28, 2019|2 min read

Convert String to Integer - atoi - Leet Code Solution

TL;DR

Skip leading whitespace, handle optional +/- sign, parse digits while checking for 32-bit integer overflow. Return clamped MIN/MAX on overflow.

Convert String to Integer - atoi - Leet Code Solution

Problem Statement

Implement atoi which converts a string to an integer.

Example 1:
	Input: "42"
	Output: 42

Example 2:
	Input: "   -42"
	Output: -42

Example 3:
	Input: "4193 with words"
	Output: 4193

Example 4:
	Input: "words and 987"
	Output: 0

Algorithm

We need to keep in mind that header includes spaces + and - character only. And, then valid integers. Then, we need to parse integers untill found. If any other character found, it is neglected.

Two special conditions: if the result is out of range (integer overflow, positive), Integer’s max value is returned if number is negative and overflow happened, return max negative value of integer.

  • Keep a flag till when we found the first valid integer
  • After this encounter, if we got any other character. Just return from there.
  • Need to keep the Overflow condition

Code

public class Q8_StringToInteger {
	public int myAtoi(String str) {
		int s = 0;
		boolean neg = false;
		boolean foundFirstValidInteger = false;
		int l = str.length();
		
		for (int i=0; i<l; i++) {
			char c = str.charAt(i);
			
			if (!foundFirstValidInteger) {
				if (c == ' ') continue;
				if (c == '+') {
					foundFirstValidInteger = true;
					continue;
				}
				if (c == '-') {
					foundFirstValidInteger = true;
					neg = true;
					continue;
				}
			}
			
			if (c >= '0' && c <= '9') {
				foundFirstValidInteger = true;
				int num = c - '0';
				
				if (s > Integer.MAX_VALUE/10 || (s == Integer.MAX_VALUE/10 && num > 7)) {
					if (neg) return Integer.MIN_VALUE;
					return Integer.MAX_VALUE;
				}
				s = s*10 + num;
			}
			else if (!foundFirstValidInteger) {
				return 0;
			}
			else {
				if (neg) return -s;
				
				return s;
			}
		}
		
		if (neg) return -s;
		
		return s;
	}
}

Output

"    -42" -> -42
debug 2
"42" -> 42
debug 1
"4193 with words" -> 4193
"words and 987" -> 0
"-91283472332" -> -2147483648
debug 1
"3.14159" -> 3
debug 1
"+-2" -> 0
"  -0012a42" -> -12
"2147483648" -> 2147483647

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…