• C语言-数字字符串转换成这个字符串对应的数字(十进制、十六进制)


    数字字符串转换成这个字符串对应的数字(十进制、十六进制)

    (1)数字字符串转换成这个字符串对应的数字(十进制)

    要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

    提示:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。

    思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

    代码如下:

    #include <stdio.h>
    #include <assert.h>
    int my_atoi(char *str)
    {
        int n = 0;
        int flag = 0;
        assert(str);
        if(*str == '-')
        {
            flag = 1;
            str++;
        }
        while(*str >= '0' && *str <= '9')
        {
            n = n*10 + (*str - '0');
            str++;
        }
        if(flag == 1)
        {
            n = -n;
        }
        return n;
    }
    int main ()
    {
        char a[] = "12";
        char b[] = "-123";
        printf("%d
    %d
    ",my_atoi(a),my_atoi(b));
        return 0;
    }

    (2)数字字符串转换成这个字符串对应的数字(十六进制)

    要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

    提示:你每发现一个数字,把当前值乘以16,并把这个值和新的数字所代表的值相加。

    思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

    代码如下:

    #include <stdio.h>
    #include <assert.h>
    #include <iostream>
    
    using namespace std;
    
    int change(char* str)
    {
        assert(str);
        int result = 0;
        int flag = 0;
    
        if (*str == '-') 
        {
            flag = 1;
            str++;
        }
    
        while (*str) 
        {
            if (*str >= '0' && *str <= '9')
                result = result * 16 + (*str - '0');
            else if (*str >= 'a' && *str <= 'f')
                result = result * 16 + (*str - 'a' + 10);
            else if (*str >= 'A' && *str <= 'F')
                result = result * 16 + (*str - 'A' + 10);
            else {
                cout << "非法字符!" << endl;
                return 0;
            }
            str++;
        }
    
        if (flag == 1) result = -result;
    
        return result;
    }
    
    int main()
    {
        char str[] = "-16";
        int res = change(str);
        cout << res << endl;
    
        return 0;
    }
  • 相关阅读:
    - > 听学姐讲那过去的故事——打代码的小女孩
    - > 强烈推荐!!!
    - > 贪心基础入门讲解五——任务执行顺序
    - > 贪心基础入门讲解二——活动安排问题
    - > 贪心基础入门讲解三——活动安排问题二
    - > 贪心基础入门讲解四——独木舟问题
    django装饰器
    POJ——T2421 Constructing Roads
    洛谷——P3258 [JLOI2014]松鼠的新家
    BZOJ——1787: [Ahoi2008]Meet 紧急集合
  • 原文地址:https://www.cnblogs.com/zkfopen/p/11060685.html
Copyright © 2020-2023  润新知