【字符串1】atoi的实现
来源:互联网 发布:淘宝如何参加天天特价 编辑:程序博客网 时间:2024/06/04 00:29
【思路】函数功能很简单,但是要考虑各种特殊条件,至少注意几点:
1、空格。开头结尾的空格要忽略,中出现空格视为非法字符
2、符号。处理开头的正负号,正负号应紧跟数字,正负号出现在中间视为非法字符
3、非法字符。遇见非法字符,输出非法字符之前的数字,之后的数字不做处理
4、溢出。这一点是最容易忽略、最难处理的情况。不能简单的计算出一遍num后就直接和INT_MAX或者INT_MIN作对比,因为num = num*10 + c这一步就可能已经溢出,产生语法错误,所以采用INT_MAX除来代替num的乘。
下面是一组输入和预期输出
【链接】http://blog.csdn.net/v_july_v/article/details/9024123
int StrToDecInt(const char* str) { static const int MAX = (int)((unsigned)~0 >> 1); //INT_MAX is ok static const int MIN = -(int)((unsigned)~0 >> 1) - 1; //INT_MIN is ok unsigned int n = 0; int sign = 1; int c; while (isspace(*str)) ++str; if (*str == '+' || *str == '-') { if (*str == '-') sign = -1; ++str; } while (isdigit(*str)) { c = *str - '0'; if (sign > 0 && (n > MAX/10 || (n == MAX/10 && c > MAX%10))) { n = MAX; break; } else if (sign < 0 && (n > (unsigned)MIN/10 || (n == (unsigned)MIN/10 && c > (unsigned)MIN%10))) { n = MIN; break; } n = n * 10 + c; ++str; } return sign > 0 ? n : -n; }
【ps】老天助我啊,嘎嘎,10.15号百度三面居然就考了这个题。。。
- 【字符串1】atoi的实现
- atoi-字符串转Int的实现
- atoi字符串转整数实现
- //实现一个atoi的函数,atoi是将字符串转换成整数
- 字符串转换成整数(atoi)函数的具体实现
- 字符串string转整数int 实现自己的atoi函数
- atoi() itoa() 的实现
- atoi函数的实现
- atoi的实现
- atoi()函数的实现
- atoi()函数的实现
- atoi的自我实现
- atoi函数的实现
- atoi函数的实现
- atoi的实现
- atoi函数的实现
- atoi函数的实现
- atoi 的实现
- O(n)求最长回文字串
- 安装VM-tools
- Remove '@override' annotation解决办法
- 第七周 求两个数正差值的程序
- 比较详细Python正则表达式操作指南(re使用)
- 【字符串1】atoi的实现
- C++内存分配的五种方法 与 c++内存问题
- USB class总结
- c++之虚析构函数
- the connection to adb is down,you must restart adb and eclipse
- JVM垃圾回收
- 类型转换
- backgroundworker使用 实现进度条ProgressBar
- nsnumber 札记