zoukankan      html  css  js  c++  java
  • atoi 和 itoa的实现

    atoi 和 itoa是面试笔试经常要考到的题目,下面两份代码是用C语言实现的atoi和itoa:

    1, atoi

    原型: int atoi(const char *nptr);

    函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。

    #include <stdio.h>
    #include <assert.h>
    static int atoi(const char* str)
    {
    int result = 0;
    int sign = 0;
    assert(str != NULL);
    // proc whitespace characters
    while (*str==' ' || *str==' ' || *str==' ')
    ++str;

    // proc sign character
    if (*str=='-')
    {
    sign = 1;
    ++str;
    }
    else if (*str=='+')
    {
    ++str;
    }

    // proc numbers
    while (*str>='0' && *str<='9')
    {
    result = result*10 + *str - '0';
    ++str;
    }

    // return result
    if (sign==1)
    return -result;
    else
    return result;
    }

    2. itoa

    char *itoaint value, char *string,int radix);

      原型说明:

      value欲转换的数据。

      string:目标字符串的地址。

      radix:转换后的进制数,可以是10进制、16进制等

    char *itoa(int val, char *buf, unsigned radix)
    {
    char *p;
    char *firstdig;
    char temp;
    unsigned digval;
    p = buf;
    if(val <0)
    {
    *p++ = '-';
    val = (unsigned long)(-(long)val);
    }
    firstdig = p;
    do{
    digval = (unsigned)(val % radix);
    val /= radix;

    if (digval > 9)
    *p++ = (char)(digval - 10 + 'a');
    else
    *p++ = (char)(digval + '0');
    }while(val > 0);

    *p-- = ' ';
    do{
    temp = *p;
    *p = *firstdig;
    *firstdig = temp;
    --p;
    ++firstdig;
    }while(firstdig < p);
    return buf;
    }

  • 相关阅读:
    git 命令图解
    tensorflow 保存及其加载
    tensorflow estimator 与 model_fn 是这样沟通的
    面向过程、面向函数、面向对象的区别浅谈
    Python 中自定义spark转换器
    pyspark 好用多了,放弃scala
    variable_scope 与 name_scope 区别
    tensorflow 条件语句与循环语句
    html 标签内部元素上下居中
    html 标签内部元素左右居中
  • 原文地址:https://www.cnblogs.com/klcf0220/p/5620524.html
Copyright © 2011-2022 走看看