zoukankan      html  css  js  c++  java
  • 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; }

     

  • 相关阅读:
    C++内存泄露的有效预防方法:谁使用,谁删除 (1.2)
    工作日志2014-08-28
    【2012.1.24更新】不要再在网上搜索eclipse的汉化包了!
    关于ActionContext.getContext()的使用方法心得
    Android开发(20)--RadioGroup的使用
    站点防止攻击
    小强的HTML5移动开发之路(50)——jquerymobile页面初始化过程
    我是怎样成长为系统架构师的
    辛星站点架构师笔记第四篇
    strcpy_s与strcpy的比較
  • 原文地址:https://www.cnblogs.com/anorthwolf/p/3123812.html
Copyright © 2011-2022 走看看