• Write your own atoi()


    he atoi() function takes a string (which represents an integer) as an argument and returns its value.

    Following is a simple implementation. We initialize result as 0. We start from the first character and update result for every character.

    // A simple C++ program for implementation of atoi
    #include <stdio.h>
     
    // A simple atoi() function
    int myAtoi(char *str)
    {
        int res = 0; // Initialize result
     
        // Iterate through all characters of input string and update result
        for (int i = 0; str[i] != '\0'; ++i)
            res = res*10 + str[i] - '0';
     
        // return result.
        return res;
    }
     
    // Driver program to test above function
    int main()
    {
        char str[] = "89789";
        int val = myAtoi(str);
        printf ("%d ", val);
        return 0;
    }

    Output:

    89789

    The above function doesn’t handle negative numbers. Following is a simple extension to handle negative numbers.

    // A C++ program for implementation of atoi
    #include <stdio.h>
     
    // A simple atoi() function
    int myAtoi(char *str)
    {
        int res = 0;  // Initialize result
        int sign = 1;  // Initialize sign as positive
        int i = 0;  // Initialize index of first digit
         
        // If number is negative, then update sign
        if (str[0] == '-')
        {
            sign = -1; 
            i++;  // Also update index of first digit
        }
         
        // Iterate through all digits and update the result
        for (; str[i] != '\0'; ++i)
            res = res*10 + str[i] - '0';
       
        // Return result with sign
        return sign*res;
    }
     
    // Driver program to test above function
    int main()
    {
        char str[] = "-123";
        int val = myAtoi(str);
        printf ("%d ", val);
        return 0;
    }

    Output:

    -123

    The above implementation doesn’t handle errors. What if str is NULL or str contains non-numeric characters. Following implementation handles errors.

    // A simple C++ program for implementation of atoi
     
    #include <stdio.h>
     
    // A utility function to check whether x is numeric
    bool isNumericChar(char x)
    {
        return (x >= '0' && x <= '9')? true: false;
    }
     
    // A simple atoi() function. If the given string contains
    // any invalid character, then this function returns 0
    int myAtoi(char *str)
    {
        if (*str == NULL)
           return 0;
     
        int res = 0;  // Initialize result
        int sign = 1;  // Initialize sign as positive
        int i = 0;  // Initialize index of first digit
     
        // If number is negative, then update sign
        if (str[0] == '-')
        {
            sign = -1;
            i++;  // Also update index of first digit
        }
     
        // Iterate through all digits of input string and update result
        for (; str[i] != '\0'; ++i)
        {
            if (isNumericChar(str[i]) == false)
                return 0; // You may add some lines to write error message
                          // to error stream
            res = res*10 + str[i] - '0';
        }
     
        // Return result with sign
        return sign*res;
    }
     
    // Driver program to test above function
    int main()
    {
        char str[] = "-134";
        int val = myAtoi(str);
        printf("%d ", val);
        return 0;
    }

    Time Complexity: O(n) where n is the number of characters in input string.

    Exercise
    Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.

    This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
    If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    //c# 

    public static int myAtoi(string s) { if (string.IsNullOrEmpty(s)) { return 0; } int sign = 1; int i = 0; int r= 0; //if number is negative,then update sign. if (s[0]=='-') { sign = -1; i++; //update index of first digit. } for (; i < s.Length; i++) { if (!(s[i]>='0'&&s[i]<='9')) { return 0; } r = r * 10 + s[i]-'0'; //'1'=49;'0'=48; 'A'=65;'a'=97 } return sign * r; }

     

  • 相关阅读:
    ESP8266-12F引脚接法
    esp8266物联网开发六:让ESP32-CAM五彩斑斓
    esp8266物联网开发五:SSL保驾护航
    esp8266物联网开发四:MQTT再论部控
    esp8266物联网开发三:MQTT初窥貌容
    esp8266物联网开发二:Arduino名门正派
    esp8266物联网开发一:MicroPython初战江湖
    一些错误记录
    jimdb压测踩坑记
    Caffeine批量加载浅析
  • 原文地址:https://www.cnblogs.com/anorthwolf/p/3123812.html
Copyright © 2020-2023  润新知