zoukankan      html  css  js  c++  java
  • 算法练习-字符串转换成整数(实现atoi函数)

    练习问题来源

    https://leetcode.com/problems/string-to-integer-atoi/

    https://wizardforcel.gitbooks.io/the-art-of-programming-by-july/content/01.03.html

    要求:

    输入一个由数字组成的字符串,把它转换成整数并输出。例如:输入字符串"123",输出整数123。

    给定函数原型int StrToInt(const char *str) ,实现字符串转换成整数的功能,不能使用库函数atoi。

    解法:

     1 // ================字符串转换成整数==================
     2 // 题目描述:
     3 // 输入一个由数字组成的字符串,把它转换成整数并输出。例如:输入字符串"123",输出整数123
     4 //给定函数原型int StrToInt(const char *str) ,实现字符串转换成整数的功能,不能使用库函数atoi
     5 
     6 // 需要考虑以下几点:
     7 // 空指针输入:输入的是指针,在访问空指针时程序会崩溃,因此在使用指针之前需要先判断指针是否为空。
     8 // 正负符号:整数不仅包含数字,还有可能是以'+'或'-'开头表示正负整数,因此如果第一个字符是'-'号,则要把得到的整数转换成负整数。
     9 // 非法字符:输入的字符串中可能含有不是数字的字符。因此,每当碰到这些非法的字符,程序应停止转换。
    10 // 整型溢出:输入的数字是以字符串的形式输入,因此输入一个很长的字符串将可能导致溢出
    11 int StrToInt(const char *str)
    12 {
    13     static const int MAX_INT = (int)((unsigned)~0 >> 1);
    14     static const int MIN_INT = -(int)((unsigned)~0 >> 1) - 1;
    15     unsigned int n = 0;
    16 
    17     // 判断输入是否为空
    18     if(0 == str)
    19     {
    20         return 0;
    21     }
    22 
    23     // 处理空格
    24     while (' ' == *str)
    25         ++str;
    26 
    27     // 处理正负
    28     int sign = 1;
    29     if('+' == *str || '-' == *str)
    30     {
    31         if(*str == '-')
    32             sign = -1;
    33         ++str;
    34     }
    35 
    36     // 检测之后的所有字符是否为 0~9
    37     const char *strDetect = str;
    38     if (*strDetect <= '0' || *strDetect > '9')
    39     {
    40         return 0;
    41     }
    42     else
    43     {
    44         ++strDetect;
    45         while((*strDetect >= '0' && *strDetect <= '9') && ('' != *strDetect))
    46         {
    47             ++strDetect;
    48         }
    49         if('' != *strDetect)
    50             return 0;
    51     }
    52 
    53     while (*str >= '0' && *str <= '9')
    54     {
    55         // 处理溢出
    56         int c = *str - '0';
    57         if(sign > 0 && (n > MAX_INT / 10 || (n == MAX_INT / 10 && MAX_INT %10)))
    58         {
    59             n = MAX_INT;
    60             break;
    61         }
    62         else if (sign < 0 && (n > (unsigned)MIN_INT / 10 || 
    63             (n == (unsigned)MIN_INT /10 && (unsigned)MIN_INT % 10)))
    64         {
    65             n = MIN_INT;
    66             break;
    67         }
    68 
    69         // 把之前得到的数字乘以10,再加上当前字符表示的数字
    70         n = n * 10 + c;
    71         ++str;
    72     }
    73 
    74     return sign > 0 ? n : -n;
    75 }

  • 相关阅读:
    【Java基础】static关键字相关
    【Java基础】foreach循环
    【Java基础】可变参数
    Android的启动模式(下)
    Android的启动模式(上)
    Universal-Image-Loader完全解析(下)
    Universal-Image-Loader完全解析(上)
    布局优化之ViewStub、Include、merge使用分析
    人在千锋--网络学习之开发项目爱限免
    4_2网络学习第二天--XML解析
  • 原文地址:https://www.cnblogs.com/nobodyzhou/p/5469234.html
Copyright © 2011-2022 走看看