Skip to main content

Command Palette

Search for a command to run...

Strings - Implement Atoi Function

Published
1 min read
Strings - Implement Atoi Function
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Implement Atoi Function

https://www.codingninjas.com/studio/problems/implement-atoi-function_981270?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTabValue=PROBLEM

Code:

#include<bits/stdc++.h>
int createAtoi(string s) {
    // Write your code here.
    int n = s.size();

    bool isSign = false;
    char sign = '+';

    int num = 0;
    int cnt = 0;

    for(int i=0;i<n;i++){
        if(num>0 && (s[i]<48 || s[i]>57)){
            if(sign=='-'){
                return -1*num;
            }
            return num;
        }

        if(isSign && (s[i]<48 || s[i]>57) ){
            return 0;
        }

        if(s[i]=='-' || s[i]=='+'){
            isSign = true;
            sign = s[i];
            continue;
        }

        if(s[i]>=48 || s[i]<=57){
            int val = s[i]-48;

            if( sign== '-' && -num<=INT_MIN/10){
                return INT_MIN;
            }
            else if(sign == '+' && num>= INT_MAX/10){
                return INT_MAX;

            }
            num = (num*10+val);
        }
    }

    if(sign=='-'){
        return -1*num;
    }
    return num;
}

DSA prep

Part 12 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters Problem Link: https://www.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article Hint: Use an array of s...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.