zoukankan      html  css  js  c++  java
  • 面试题目字符串与整型互转

    ///////////////////////////////////////////////////////////////////////////////
    //
    //  FileName    :   atoi_itoa.cpp
    //  Version     :   0.10
    //  Author      :   Ryan Han
    //  Date        :   2014/07/06 23:36
    //  Comment     :  
    //
    ///////////////////////////////////////////////////////////////////////////////
    #include <stdio.h> // printf
    #include <ctype.h> // isspace(), isdigit()
     
    int atoi(char s[])
    {
        int i, n, sign;
        //skip the space
        for(i=0; isspace(s[i]); i++)
            ;
        //store the sign
        sign = (s[i] == '-') ? -1 : 1;
        //skip the sign
        if(s[i] == '+' || s[i] == '-')
            s++;
        //calculate the number
        for(n = 0; isdigit(s[i]); i++)
            n = 10*n + (s[i] - '0');
        return sign * n;
    }
     
    void itoa(int n, char s[])
    {
        int i, j, sign;
        //store the sign, convert to positive num
        if((sign = n ) < 0)
            n = -n;
        //store the number in reverse order
        i = 0;
        do{
            s[i++] = n%10 + '0';
        }while((n/=10) > 0);
        //store the sign
        if(sign < 0)
            s[i++] = '-';
        //put the end sign
        s[i] = '\0';
        //output in reverse order
        for(j = i; j >= 0; j--)
            printf("%c", s[j]);
    }
     
    int main()
    {
        int i = 0;
        char s[] = "1234";
        i = atoi(s);
        printf("The atoi test: \n");
        printf("The atoi of \"1234\" is: %d", i);
     
        printf("\n");
        printf("The itoa test: \n");
        int j = -5678;
        char t[10];
        itoa(j, t);
     
        return 0;
    }
    

      

  • 相关阅读:
    C++---使用类
    C++---函数
    C++---指针和引用
    C++---面向对象
    C++---数组
    C++---条件结构和循环结构
    C++---变量、数据类型和运算符
    C++---初识C++
    MySQL---什么是事务
    MySQL---char和varchar的区别
  • 原文地址:https://www.cnblogs.com/dracohan/p/2985818.html
Copyright © 2011-2022 走看看