Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

Leetcode String to Integer (atoi) problem solution

YASH PAL, 31 July 2024

In this Leetcode String to Integer (atoi) problem solution we need to implement the myAtoi(string s) function that converts a string to a 32 bit signed integer.

Leetcode String to Integer (atoi) problem solution

Problem solution in Python.

class Solution:
    def validCharacter(self, ch):
        return ord('0') <= ord(ch) <= ord('9')
    
    def myAtoi(self, s: str) -> int:
        l = list(s)
        
        # remove whitespace
        while l and l[0] == " ":
            l.pop(0)
            
        # specify sign
        sign = 1
        if l and l[0] == '+':
            l.pop(0)
            sign = 1
        elif l and l[0] == '-':
            l.pop(0)
            sign = -1
        
        buf = ""
        while l and self.validCharacter(l[0]):
            buf += l.pop(0)
        
        result = 0
        for i in buf:
            num = ord(i) - ord('0')
            result = result* 10 + num
        result *= sign  # add sign
        if result > 2 ** 31 - 1:
            return 2 ** 31 - 1
        elif result < -(2 ** 31):
            return -(2 ** 31)
        else:
            return result

Problem solution in Java.

int start = 0, sign = 1;
        long res = 0;
        while(start < s.length() && s.charAt(start) == ' ') {
            start++;
        }
        
        if(start < s.length() && s.charAt(start) == '+') {
            start++;
        } else if(start < s.length() && s.charAt(start) == '-') {
            sign = -1;
            start++;
        }
        
        while(start < s.length()) {
            if(!Character.isDigit(s.charAt(start))) break;
            res *= 10;
            res += s.charAt(start) - '0';
            if(res > Integer.MAX_VALUE) {
                if(sign == 1) return Integer.MAX_VALUE;
                return Integer.MIN_VALUE;
            }
            start++;
        }
        
        return (int) res * sign;

Problem solution in C++.

class Solution {
public:
    int myAtoi(string str) {
        long long ans =0;
        bool isNeg = false;
        int i=0;
        while(str[i]==' ')
            i++;
        
        if(str[i]=='-'){
            isNeg = true;
            i++;
        }
            
        else if(str[i]=='+'){
            isNeg = false;
            i++;
        }
        while(str[i]=='0')
            i++;
        
        int end=0;
        for( end=i;end<str.size();end++){
             if(str[end]>'9'||str[end]<'0')
            break;
        }
        if(end-i>12){
            if(isNeg)
                return INT_MIN;
            else return INT_MAX;
        }
        for(int j=i;j<str.size();j++){
          if(str[j]>'9'||str[j]<'0')
            break;
            
            ans = 10*ans + str[j]-'0';
           
        }
         if(isNeg)
                return (INT_MIN>-ans?INT_MIN:-ans);
            else
                return (INT_MAX>ans?ans:INT_MAX);
       
    }
};

Problem solution in C.

int myAtoi(char *str) {
    int flag = 1;
    long res = 0;
    
    if (str == NULL) return 0;
    while (*str == ' ' || *str == 't') ++str;
    if (str == NULL) return 0;
    if (*str != '-' && *str != '+' && (*str < '0' || *str >'9')) return 0; 
    if (*str == '-') {flag = -1;++str;}
    else if (*str == '+') {flag = 1; ++str;}
    if (str == NULL) return 0;
    
    int cnt = 0;  
    while(*str) {
        if (*str < '0' || *str >'9') break;
        res = res * 10 + *str - 0x30;
        ++str;
        ++cnt;
    }
    
    if (cnt > 10) return flag == 1 ? INT_MAX : INT_MIN;
    
    res *= flag;
    if (res > INT_MAX) return INT_MAX;
    if (res < INT_MIN) return INT_MIN;
    

    return (int)res;
}

coding problems solutions

Post navigation

Previous post
Next post

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes