c - 优化我自己的atoi

标签 c

    int myAtoi2(char *str)
    {
        int number = 0;
        char *ptr = str;

        if ( *ptr == '-' ) {
          number = number - ( *++ptr - '0' );
          ptr++;
        }

        while ( isdigit ( *( ptr ) ) ){
          if ( number < 0 ) {
            number = number * 10 - (*ptr++ - '0');
          }
          else
            number = number * 10 + (*ptr++ - '0');
        }

       return number;
   }

有什么方法可以让我自己的 atoi 更好(也许是干净的代码和更好的性能)?

最佳答案

它可以像这样从根本上简化。您只需要解析字符串一次,并维护一个值。这是针对无符号值的。如果您想要负数和范围检查,则需要在代码中添加更多内容。

#include <stdio.h>
#include <ctype.h>

unsigned myOwnAtoi( char *str )
{
    unsigned number = 0;
    char *ptr = str;
    while(isdigit(*ptr)) {
        number = number * 10 + *ptr++ - '0';
    }
    return number;
}

int main(void)
{
    printf("%u\n", myOwnAtoi("123456"));
    return 0;
}

程序输出:

123456

关于c - 优化我自己的atoi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120476/

相关文章:

c - 使用 fread 将文件的一部分读取到缓冲区

c++ - openssl 客户端如何信任服务器的自签名证书

c - 在 OpenCV 中使用直方图数据跟踪对象

c++ - Makefile:无规则可作为目标

c - 如何将字符串数组形式的特定元素的地址传递给另一个函数

objective-c - 我可以将 C 数组添加到 objective-C NSArray 中吗?

C语言: Search text file for a "var" and store the next string as the value

c - Typedef 函数指针 - 使用与不使用之间的区别

c++ - C++ 中的简单数组使用?

c - 格式错误的 DNS 响应