Facebook :实现atoi函数
2015-07-28 21:39
260 查看
一、
二、
class CException { public: CException(const char* str) : m_strErr(str) {} string GetErrInfo() { return m_strErr; } private: std::string m_strErr; }; int myatoi(const char* p) { assert(p); int nFlg = 1; if ('-' == *p) nFlg = -1; if ('-' == *p || '+' == *p) p++; if ('\0' == *p) throw CException("Invalid expression"); int nRet = 0; while('\0' != *p) { if (*p < '0' || *p > '9') throw CException("Invalid character"); int nVal = *p - '0'; int nNew = nRet*10 + nFlg * nVal; if (nRet != 0 && ((nNew & 0x80000000) != (nRet & 0x80000000))) throw CException("Integer over flow"); nRet = nNew; p++; } return nRet; }
二、
int atoi (char* str) { assert(str); assert(str[0]); int result = 0; int newResult = 0; if (str[0] == '+') return atoi(str + 1); if (str[0] == '-') return -1 * atoi(str + 1); int i = 0; while (str[i]) { assert(str[i] >= '0' && str[i] <= '9'); newResult = (result << 1) + (result << 3) + str[i] - '0'; assert(newResult >= result); result = newResult; i++; } return result; }
相关文章推荐
- ubuntu apt-get和aptitude 安装软件包
- Android Day10-多媒体
- 第70讲:Scala界面GUI编程实战详解
- 25.2.3.35. mysql_init() http://www.cnblogs.com/ymy124/archive/2012/04/03/2430808.html
- centos 下使用libpcap
- 数据结构实验之队列一:排队买饭 SDUT
- POJ 1061 青蛙的约会
- 作用域随笔
- SEO在网页制作中的应用
- sys.argv[]基本用法
- 开源网站访问统计系统Piwik
- 淘宝分布式框架Fourinone2.0正式版发布
- hdoj2067 小兔的棋盘【dp+打表】or卡特兰数
- 黑马程序员--iOS--C基础(程序结构)
- Android Day09四大组件之内容提供者ContentProvider
- 深入探索Linux coredump调试技巧
- 看病排队
- stdlib.h
- Oracle学习笔记+作业
- 自定义Linux 终端/ssh登录前后的欢迎信息