LeetCode题目: 8. String to Integer (atoi)
来源:互联网 发布:男士护肤套装 知乎 编辑:程序博客网 时间:2024/06/05 00:48
LeetCode题目: 8. String to Integer (atoi)
原题链接:https://leetcode.com/problems/string-to-integer-atoi/description/
解题思路:
(以下来自百度)
原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
照着上面实现即可。
核心思想:
1.先寻找到第一个非空格位置
2.判断是否有正负号,并记录正负
3.进行数字相加,每有一个新数字,sum=sum*10+newNumber。
4.给结果重新加上正负号
代码细节:
1.如果越界,返回界内最接近该值的值,例如:-2147483649—>-2147483648,2147483649—>2147483647
2.如果第一个非空格字符不是数字或正负号,或遍历到结尾,直接返回0。
3.为了判断是否越界,用longlong储存结果。(long不够长)
坑点:
1.从第一个非空格字符开始
2.无法越界,取值范围有限制
3.可以识别”+123”之类的正数
代码:
int myAtoi(string str) { bool isNegative = false; // 表示正负 long long output = 0; // 表示输出值 // 如果输入为空 if (str.empty()) return output; // 寻找第一个空格后字符位置 int i; for (i = 0; i < str.length(); i++) if (str[i] != ' ') break; // 没有找到,返回0 if (i == str.length()) return output; else if (str[i] == '+' || str[i] == '-') { if (str[i] == '-') isNegative = true; i++; } else if (!isdigit(str[i])) return output; // 进行字符相加 while (i < str.length() && isdigit(str[i])) { output *= 10; output += str[i] - '0'; i++; // 判断是否越界 if (output > 2147483648) { output = 2147483648; break; } } // 添加正负号,int取值范围为-2^32----2^32-1 if (!isNegative) { if (output == 2147483648) output--; } else output = -output; return (int)output;}
阅读全文
0 0
- LeetCode题目: 8. String to Integer (atoi)
- LeetCode算法题目:String to Integer (atoi)
- LeetCode题目:String to Integer (atoi)
- LeetCode题目:String to Integer (atoi)
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- 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] 8.String to Integer (atoi)
- <LeetCode OJ> 8. String to Integer (atoi)
- leetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) LeetCode
- leetcode 8. String to Integer (atoi)
- leetcode 8. String to Integer (atoi)
- LeetCode OJ 8.String to Integer (atoi)
- codeforces 859A Declined Finalists
- LeetCode题目: 7.Reverse Integer
- vi中如何跳转到指定行数
- 测试
- HDU 5521 Meeting 建图+最短路
- LeetCode题目: 8. String to Integer (atoi)
- You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.
- Eclipse中打开.class文件的方法
- 数据库连接池技术介绍(空间换时间)
- 实验二:命令行菜单小程序V1.0
- 机器学习
- LeetCode题目:9.Palindrome Number
- 插件SQLScout使用
- 线程中调用Toast闪退解决方案