Question:
How to implement Atoi function in C?

Summary:

The given C++ code defines a class Solution with a member function atoi that converts a string to an integer, mimicking the behavior of the standard library's atoi function. The code handles both positive and negative integers and checks for invalid characters in the string. The function returns the converted integer or -1 if the string contains non-numeric characters.


Solution:

//User function template for C++


class Solution{

  public:

    /*You are required to complete this method */

    int atoi(string s) {

        //Your code here

        int sign = 1;

        if(s[0] == '-'){

            sign = -1;

            s = s.substr(1);

        }

        int num = 0;

        for(int i=0;i<s.length();i++){

            if(s[i] >= '0' && s[i] <= '9'){

                num = num*10 + (s[i]-'0');

            }

            else{

                return -1;

            }

        }

        return num*sign;

    }

};


Explanation:

  • The atoi function takes a string s as input and converts it into an integer.

  • It checks if the first character of the string is '-' to determine the sign of the integer.

  • If the string is negative, it updates the sign variable and removes the '-' from the string using substr(1).

  • The function then iterates through each character in the string, converting it to its numeric value and updating the final integer.

  • If a non-numeric character is encountered during the iteration, the function returns -1, indicating an invalid input.

  • Finally, the function returns the calculated integer value with the correct sign.


Answered by: >kjindalagg

Credit:> >Geeksforgeeks


Suggested blogs:

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?


Submit
0 Answers
Top Questions
How to implement Atoi function in C?
img