StrToInt实现
2016-04-04 21:28
225 查看
StrToInt实现
字符串转整型数的整体思想很简单,但是实现起来,细节问题很容易忽略,故写此博客来加深记忆。- 细节处理
参数中const变量指针使用;
空指针处理;
字符串前面空格处理;
字符串正负号处理;
字符前面 0 字符的处理;
最大整数和最大负数溢出处理;
错误字符输入处理
- 函数实现
int StrToInt(const char *str) { int result = 0; int flag = 1; // 判断字符串是否是NULL if (str == NULL) { return -1; } // 跳过前面的空格 while ((*str) == ' ') str++; // 判断字符串正负号 if ((*str) == '-') { flag = -1; str++; } if ((*str) == '+') { flag = 1; str++; } // 跳过字符串前面的0 while ((*str) == '0') { str++; } // 遍历剩下字符串,进行字符转数字 while((*str) != '\0') { // 判断字符是否合法 if ((*str >= '0') && (*str <= '9')) { int temp = result; // 正数处理 if (flag == 1) { result = (result * 10) + (*str - '0'); } // 负数处理 else if (flag == -1) { result = (result * 10) - (*str - '0'); } // 溢出判断 if (((flag == 1) && (result < temp)) || ((flag == -1) && (result > temp))) return -1; str++; } else { return -1; } } return result; }
相关文章推荐
- 【剑指offer】字符串转整数
- c字符串转整数
- 算法习题20:把字符串转换成整数并输出
- Leet Code 8 String to Integer - 字符串转整数 - Java
- 《编程之法》1.4字符串转换成整数
- LeetCode 8. String to Integer (atoi)
- 剑指offer 把字符串转换成整数
- leetcode 8. String to Integer (atoi)
- [LeetCode]--8. String to Integer (atoi)
- [Leetcode #8]String to Integer (atoi) 字符串转整数
- [Leetcode #8]String to Integer (atoi) 字符串转整数
- LeetCode-String to Integer (atoi)-My Java Solution
- 字符串转整数
- socket编程基于UDP的服务端客户端回声程序
- 关于基本控件TextView属性大全详解
- lldb
- 构建之法阅读笔记04
- leetcode020 Valid Parentheses
- Light OJ 1230 Placing Lampposts(简单树形DP)
- WPF MVVM中在ViewModel中关闭或者打开Window