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; }

     

  • 相关阅读:
    遍历切片slice,结构体struct,映射map,interface{}的属性和值
    [转]Go语言string,int,int64 ,float之间类型转换方法
    [转] golang中struct、json、map互相转化
    [转]Jupyter默认目录和默认浏览器修改
    sublime text3输出窗口中文显示乱码问题解决方案
    Oracle 在SQL语句中如何获取系统当前时间并进行操作
    eclipse调试的时候怎么后退?
    外部无法访问虚拟机8088和50070端口
    hadoop启动后jps查不到namenode的解决办法
    Java给整数部分的字符串加上千分位分隔符
  • 原文地址:https://www.cnblogs.com/anorthwolf/p/3123812.html
Copyright © 2011-2022 走看看