zoukankan      html  css  js  c++  java
  • 关于把字符串整数转换成整数的程序

    前几天去了先锋商泰面试,在面试时做了一个把输入的整数(例如:4238)重新排序成2348输出的题目。

    由于自己没有准备充分,只是把功能写出来了。后来没有拿到offer。

    今天在看《剑指offer》时,发现自己少了很多边界条件和错误的处理。在剑指offer这本书上有个题目:

    题目:把一个字符串转换成整数。
    下面是要注意的事项:不能只完成基本的要求,还要考虑最大整数和最小负整数以及溢出。以及当输入字符串不能转换成整数时,应该如何做错误处理。

    我花了一些时间,写了下面这个程序,希望大家能一起交流,如果有问题,可以加以指正。谢谢!


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>


    int StrToInt(char *str);


    int main(int argc, const char *argv[])
    {
    char *str;
    int num = 0;
    str = (char *)malloc(sizeof(char) * 100);//为指针申请堆空间
    if(str == NULL)
    {
    perror("malloc");
    exit(-1);
    }
    scanf("%s",str);//从终端接收字符数据
    num = StrToInt(str);//调用函数
    printf("this num is %d ",num);
    free(str);


    return 0;
    }


    int StrToInt(char *str)
    {
    int num = 0;
    int symbol = 1;
    if( str == NULL )//检验是否为空指针
    {
    perror("str is null");
    exit(-1);
    }
    if(*str == '-')//检验正负
    {
    symbol = -1;
    str ++;
    }
    if(strlen(str) > 10 || strlen(str) == 10 && *str > '2')//检验输入的整数是否超过范围
    {
    perror("this integer is too big");
    exit(-1);
    }




    while( *str != 0 )//如果字符串没有结束,则继续
    {
    if(*str >= 48 && *str <= 58 && symbol == 1)//如果字符是0~9且为正数
    {
    num = num * 10 + *str - '0';//加
    ++str;
    }
    else if (*str >= 48 && *str <= 58 && symbol == -1)//如果字符是0~9且为负数
    {
    num = num * 10 - *str + '0';//直接减
    ++str;
    }
    else//如果有非0~9的字符,则报错退出
    {
    perror("this is not a number");
    exit(-1);
    }
    }


    if( symbol == 1 )//看是否超过2147483647,若超过,则num变为负数(前面已经限定num的绝对值不超过3000000000)
    {
    if( num < 0 )
    {
    perror("is up overflow");
    exit(-1);
    }
    }
    if( symbol == -1 )//看是否超过-2147483648,若超过,则num变为正数(同上)
    {
    if( num > 0 )
    {
    perror("is down overflow");
    exit(-1);
    }
    }
    return num;//返回值
    }

  • 相关阅读:
    函数嵌套
    函数对象
    可变长参数
    函数的参数
    函数的调用
    函数的返回值
    定义函数的三种形式
    函数的定义
    SQLAlchemy
    Flask总结完整版
  • 原文地址:https://www.cnblogs.com/vonyao/p/3614334.html
Copyright © 2011-2022 走看看