• 源码实现 --> atoi函数实现


    atoi函数实现

      atoi()函数的功能是将一个字符串转换为一个整型数值。

    例如“12345”,转换之后的数值为12345,“-0123”转换之后为-123。

    #include <stdio.h>
    int my_atoi(const char *str) { int total = 0; //保存转换后的数值 int isNegative = 0; //记录字符串中是否有负号 int length = 0; //记录字符串的长度 const char *p = str; char temp = '0'; if(NULL == p) //判断指针的合法性 { printf("error"); return -1; } while(*p++!='') //计算字符串的长度 { length++; } p = str; //重新指向字符串的首地址 if(*p == '-') //判断是否有负号 { isNegative = 1; } for(int i = 0;i < length;i++) { temp = *p++; if(temp > '9'||temp < '0') //滤除非数字字符 { continue; } if(total != 0||temp != '0') //滤除字符串开始的0字符 { temp -= '0'; total = total*10 + temp; } } if(isNegative) //如果字符串中有负号,将数值取反 return (0 - total); else return total; //返回转换后的数值 } int main(int argv,char *argc[]) { printf("%d ",my_atoi("-0123")); return 0; }

    执行结果:-123

  • 相关阅读:
    64位整数乘法
    HTML中常见问题汇总贴
    题解 牛客【「水」悠悠碧波】
    题解 CF1391B 【Fix You】
    四级-句子
    快速幂||取余运算
    最大子列和
    JvavScript中的函数与对象
    JavaScript中的流程控制语句
    冒泡排序,选择排序,插入排序,归并排序
  • 原文地址:https://www.cnblogs.com/jeakeven/p/5332860.html
Copyright © 2020-2023  润新知