leetcode String to Integer (atoi) 字符串转整数
2017-10-11 11:25
375 查看
Implement atoi to convert a string to an integer.
题意:将一个字符串转换为int型整数
思路:
1、字符串开头的空格省去
2、字符串非空格开头是否为正负号
3、上越界返回INT_MAX,下越界返回INT_MIN
4、字符串含非法字符,返回非法字符之前字符串构成的数字
题意:将一个字符串转换为int型整数
思路:
1、字符串开头的空格省去
2、字符串非空格开头是否为正负号
3、上越界返回INT_MAX,下越界返回INT_MIN
4、字符串含非法字符,返回非法字符之前字符串构成的数字
class Solution { public: int myAtoi(string str) { int sign = 1, base = 0, i = 0; while (str[i] == ' ') i++;//找到第一个非空格字符 if (str[i] == '-' || str[i] == '+')//判断是否为正负号 sign = 1 - 2 * (str[i++] == '-'); while (str[i] >= '0' && str[i] <= '9') {//判断字符串是否合法 if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {//判断是否越界,此处下界为-2147483648,应加一判断条件,不加在leeetcode通过 if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign; } };
相关文章推荐
- [LeetCode-8] String to Integer (atoi,字符串转成整数)
- 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】
- [LeetCode] String to Integer (atoi) 字符串转为整数
- 【LeetCode】8. String to Integer (atoi) 字符串转换为整数
- 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】
- leetcode8- String to Integer (atoi 字符串转整数)
- leetcode:String to Integer (atoi) 字符串转化成整数
- [LeetCode] 8. String to Integer (atoi) 字符串转为整数
- LeetCode String to Integer (atoi) 字符串转换整数
- LeetCode 8. String to Integer (atoi) (字符串到整数)
- LeetCode 8. String to Integer (atoi)(字符串转整数)
- String to Integer (atoi) 字符串转整数
- Leetcode 8 String to Integer (atoi) 字符串处理
- [Leetcode #8]String to Integer (atoi) 字符串转整数
- String to Integer (atoi字符串转换为整数)
- LeetCode--String to Integer (atoi)字符串转数字
- leetcode-8-String to Integer (atop)字符串转整数
- [Leetcode #8]String to Integer (atoi) 字符串转整数
- String to Integer (atoi) 将字符串转化成整数
- LeetCode OJ String to Integer (atoi) 字符串转数字