zoukankan      html  css  js  c++  java
  • 信雅达面试题atoi函数实现

     atoi函数:

    功 能: 把字符串转换成整型数。
    名字来源:ASCII to integer 的缩写。
    原型: int atoi(const char *nptr);
    函数说明
    参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零,
     
     1 #include <stdio.h>
     2 #include <assert.h>
     3 int is_digit(char ch)
     4 {
     5     if(ch >= '0' && ch <= '9')
     6         return 1;
     7     else
     8         return 0;
     9 }
    10 int is_space(char ch)
    11 {
    12     if(ch == ' ' || '
    ' == ch || '	' == ch || '
    ' == ch || '' == ch || 'f' == ch)
    13         return 1;
    14     else
    15         return 0;
    16 }
    17 
    18 int my_atoi(const char *str)
    19 {
    20     assert(str);
    21     int sum = 0;
    22     char sign = '+';
    23 
    24     while(is_space(*str++));
    25     
    26     if(*str == '+' || *str == '-')
    27         sign = *str++;
    28 
    29     while(is_digit(*str))
    30     {
    31         sum  = sum *10 + *str - '0';
    32         str++;
    33     }
    34 
    35     if(sign == '-')
    36         return -sum;
    37     else
    38         return sum;
    39 }
    40 int main()
    41 {
    42     printf("string: %d
    ", my_atoi("+214"));
    43     return 0;
    44 }
  • 相关阅读:
    C语言I作业12—学期总结
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I作业9
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业03
  • 原文地址:https://www.cnblogs.com/xuyh/p/3258687.html
Copyright © 2011-2022 走看看