Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1604538
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: C/C++

2014-04-09 23:11:45

一、功能简介

把一个字符串转换成整数

二、linux c库函数实现

点击(此处)折叠或打开

  1. /***
  2. *long atol(char *nptr) - Convert string to long
  3. *
  4. *Purpose:
  5. * Converts ASCII string pointed to by nptr to binary.
  6. * Overflow is not detected.
  7. *
  8. *Entry:
  9. * nptr = ptr to string to convert
  10. *
  11. *Exit:
  12. * return long int value of the string
  13. *
  14. *Exceptions:
  15. * None - overflow is not detected.
  16. *
  17. *******************************************************************************/

  18. long __cdecl atol(
  19.         const char *nptr
  20.         )
  21. {
  22.         int c; /* current char */
  23.         long total; /* current total */
  24.         int sign; /* if '-', then negative, otherwise positive */

  25.         /* skip whitespace */
  26.         while ( isspace((int)(unsigned char)*nptr) )
  27.             ++nptr;

  28.         c = (int)(unsigned char)*nptr++;
  29.         sign = c; /* save sign indication */
  30.         if (c == '-' || c == '+')
  31.             c = (int)(unsigned char)*nptr++; /* skip sign */

  32.         total = 0;

  33.         while (isdigit(c)) {
  34.             total = 10 * total + (c - '0'); /* accumulate digit */
  35.             c = (int)(unsigned char)*nptr++; /* get next char */
  36.         }

  37.         if (sign == '-')
  38.             return -total;
  39.         else
  40.             return total; /* return result, negated if necessary */
  41. }


  42. /***
  43. *int atoi(char *nptr) - Convert string to long
  44. *
  45. *Purpose:
  46. * Converts ASCII string pointed to by nptr to binary.
  47. * Overflow is not detected. Because of this, we can just use
  48. * atol().
  49. *
  50. *Entry:
  51. * nptr = ptr to string to convert
  52. *
  53. *Exit:
  54. * return int value of the string
  55. *
  56. *Exceptions:
  57. * None - overflow is not detected.
  58. *
  59. *******************************************************************************/

  60. int __cdecl atoi(
  61.         const char *nptr
  62.         )
  63. {
  64.         return (int)atol(nptr);
  65. }

三、需要注意的问题(摘自剑指offer)

面试官至少会期待应聘都能够在不需要提示的情况下,考虑到输入的字符串中有非数字字符正负号,要考虑到最大的正整数最小的负整数以及溢出。同时面试试还期待应聘者能够考虑到当输入的字符串不能转换成整数时,应该如何做错误处理

1、检查字符串是否为空

2、对非法输入,返回0,并设置全局变量

3、溢出

4、空字符串""

5、输入字符串只有"+"或"-"号

 

四、剑指offer实现

点击(此处)折叠或打开
  1. // StringToInt.cpp : Defines the entry point for the console application.
  2. //

  3. // 《剑指Offer——名企面试官精讲典型编程题》代码
  4. // 著作权所有者:何海涛

  5. #include "stdafx.h"
  6. #include <stdio.h>
  7. #include <stdlib.h>

  8. long long StrToIntCore(const char* str, bool minus);

  9. enum Status {kValid = 0, kInvalid};
  10. int g_nStatus = kValid;

  11. int StrToInt(const char* str)
  12. {
  13.     g_nStatus = kInvalid;
  14.     long long num = 0;

  15.     if(str != NULL && *str != '\0')
  16.     {
  17.         bool minus = false;
  18.         if(*str == '+')
  19.             str ++;
  20.         else if(*str == '-')
  21.         {
  22.             str ++;
  23.             minus = true;
  24.         }

  25.         if(*str != '\0')
  26.         {
  27.             num = StrToIntCore(str, minus);
  28.         }
  29.     }

  30.     return (int)num;
  31. }

  32. long long StrToIntCore(const char* digit, bool minus)
  33. {
  34.     long long num = 0;

  35.     while(*digit != '\0')
  36.     {
  37.         if(*digit >= '0' && *digit <= '9')
  38.         {
  39.             int flag = minus ? -1 : 1;
  40.             num = num * 10 + flag * (*digit - '0');

  41.             if((!minus && num > 0x7FFFFFFF)
  42.                 || (minus && num < (signed int)0x80000000))
  43.             {
  44.                 num = 0;
  45.                 break;
  46.             }

  47.             digit++;
  48.         }
  49.         else
  50.         {
  51.             num = 0;
  52.             break;
  53.         }
  54.     }

  55.     if(*digit == '\0')
  56.     {
  57.         g_nStatus = kValid;
  58.     }

  59.     return num;
  60. }

  61. // ====================测试代码====================
  62. void Test(char* string)
  63. {
  64.     int result = StrToInt(string);
  65.     if(result == 0 && g_nStatus == kInvalid)
  66.         printf("the input %s is invalid.\n", string);
  67.     else
  68.         printf("number for %s is: %d.\n", string, result);
  69. }

  70. int _tmain(int argc, _TCHAR* argv[])
  71. {
  72.     Test(NULL);

  73.     Test("");

  74.     Test("123");

  75.     Test("+123");
  76.     
  77.     Test("-123");

  78.     Test("1a33");

  79.     Test("+0");

  80.     Test("-0");

  81.     //有效的最大正整数, 0x7FFFFFFF
  82.     Test("+2147483647");

  83.     Test("-2147483647");

  84.     Test("+2147483648");

  85.     //有效的最小负整数, 0x80000000
  86.     Test("-2147483648");

  87.     Test("+2147483649");

  88.     Test("-2147483649");

  89.     Test("+");

  90.     Test("-");

  91.     return 0;
  92. }
五、综合库函数及剑指offer,写出如下程序(个人作品,非标准答案)

点击(此处)折叠或打开

  1. typedef enum {VALID, INVALID} ResType;  //返回的结果类型
  2. ResType g_rtRes = VALID;

  3. bool isdigit(char ch)
  4. {
  5.   return '0'<=ch && ch<='9';
  6. }

  7. int StrToInt(const char *str)
  8. {
  9.   unsigned int iCur, iMax;
  10.   int sign;
  11.   const char *p;  

  12.   //判断参数是否合法
  13.   if(!str || strlen(str)<=0){
  14.     g_rtRes = INVALID;
  15.     return 0;
  16.   }

  17.   //去掉前面空格
  18.   for(p=str; ' '==*p; p++);

  19.   //判断正负号
  20.   sign = 1;
  21.   iMax = ~(1<<8*sizeof(int)-1);  //最大正整数  
  22.   if('+'==*p){
  23.     p++;
  24.   }else if('-' == *p){
  25.     p++;
  26.     sign = -1;
  27.     iMax = ~iMax;  // sign*iMax 就是最小负正数
  28.   }

  29.   //首位不是数字,输入非法
  30.   if(!isdigit(*p)){
  31.     g_rtRes = INVALID;
  32.     return 0;
  33.   }

  34.   //首位是0,特殊处理
  35.   if('0'==*p){
  36.     if(isdigit(*(p+1))){
  37.       g_rtRes = INVALID;      
  38.     }
  39.     return 0;
  40.   }

  41.   //累和
  42.   for(iCur=0; isdigit(*p) && iCur<=iMax; p++){
  43.     iCur = iCur*10 + (*p - '0');
  44.   }

  45.   //返回结果
  46.   if(iCur <= iMax){
  47.     return (int)(sign*iCur);
  48.   }else{
  49.     g_rtRes = INVALID;
  50.     return 0;
  51.   }
  52. }// StrToInt
http://www.cnblogs.com/niocai/archive/2012/05/04/2483133.html


阅读(1885) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~