面试经典题目 atoi实现 htoi实现
来源:互联网 发布:mac 装win10 编辑:程序博客网 时间:2024/06/06 11:01
考察点:
1. 不合法检查
a. NULL
b. ""
c. "+"
d. " "
e. "124jio"
2. 溢出情况的处理
基于上述考虑的代码如下,采用一个全局状态变量来处理不合法和溢出情况。
typedef enum{INVALID, VALID} ValidFlag;ValidFlag flag;int atoi(const char *s) { char *p; int sign; long long total; if (s == NULL || *s == '\0') return flag = INVALID; p = s; while (isspace((int)(unsigned int)*p)) p++; sign = (*p == '-') ? -1 : 1; if (*p == '+' || *p == '-'){ ++p; } if (*p == '\0') // "+" "-" " "check return flag = INVALID; total = 0; while (isdigit((int)(unsigned int)*p)) { total = total * 10 + (int)(unsigned int)*p - '0'; if (total < 0 //overflow check || total > (long long)INT_MAX + 1 && sign < 0 || total > (long long)INT_MAX && sign > 0) return flag = INVALID; p++; } if (*p == '\0') { flag = VALID; return sign == -1 ? -total : total; } return flag = INVALID; }
与此类似的htoi,只不过多了前缀0x或0X,以及需要处理a-f, A-F,别忘了total = total * 16 + *p - 'a' + 10;
typedef enum {INVALID, VALID} ValidFlag;ValidFlag flag;int htoi(const char *s) { int sign; char *p = s; long long total = 0; if (s == NULL || *s == '\0') return flag = INVALID; while(isspace(*p)) p++; sign = (*p == '-') ? -1 : 1; if (*p == '+' || *p == '-') p++; if (*p == '0' && (*(p+1) == 'X' || *(p+1) == 'x')) p += 2; if (*p == '\0') //" " "+" "0x" "-0x" check return flag = INVALID; while (*p) { if (isdigit(*p)) total = total * 16 + *p - '0'; else if ('a' <= *p && *p <= 'f') total = total * 16 + *p - 'a' + 10; else if ('A' <= *p && *p <= 'F') total = total * 16 + *p - 'A' + 10; else return flag = INVALID; if (total < 0 || total > (long long)INT_MAX && sign > 0 || total > (long long)INT_MAX + 1 && sign < 0) return flag = INVALID; p++; } if (*p == '\0') { flag = VALID; return sign > 0 ? total : -total; } return flag = INVALID;}
- 面试经典题目 atoi实现 htoi实现
- 面试常考题目之atoi的实现
- 算法题目---实现atoi函数
- 【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
- 【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
- 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】
- 题目:实现atof/atoi,考虑正负号
- 面试编程——atoi实现
- LeetCode(atoi)实现atoi
- atoi实现
- atoi实现
- atoi 实现
- 实现atoi
- atoi实现
- 实现atoi
- atoi实现
- atoi实现
- atoi实现
- 三维坐标点绕任意轴旋转的新坐标计算
- 默写nginx并逐句分析 - ngx_array
- UVa 11795 - Mega Man's Mission(状态压缩dp)
- 支持中文的PHP字符串截取函数 (附各语言的字符集编码范围)
- 解决在win7 64位系统下通过ado连接oracle出现ORA-12154错误
- 面试经典题目 atoi实现 htoi实现
- php将文字写在图片上,图片加水印
- opengl+vs2010+win7环境搭建
- Android地图开发之OpenStreetMap基础教程
- Linux平台基于S3C2440的MPlayer的移植
- Run-Time Check Failure #2 - Stack around the variable 'dlg1' was corrupted.
- UVa 572/POJ 1562/HDU 1241 Oil Deposits(DFS,两种写法)
- 用友 NC客户化开发手册
- 快速安装PHP-Mysql