LeetCode笔记:8. String to Integer (atoi)
2023-03-15 23:20:38 时间
问题:
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
大意:
实现 atoi 来将一个字符串转为一个整型。 暗示:小心考虑所有可能的输入案例。如果你想要挑战,请不要看下面的内容并问问你自己有哪些可能的输入案例。 注意:这个问题特意说的比较模糊(比如,没有给出输入规则)。你需要收集所有输入需求。
思路:
字符串转换成整型本身不难,麻烦的在于考虑到所有可能的情况并作出处理。
可能有的情况有:
- -开头的负数
- +开头的正数
- 0 开头的数字
- 空格开始的数字
- 数字直接开头
- 除了以上的情况外其余开头的都返回0
- 数字中间夹了其余非数字字符的话就不考虑后面的内容了
基于以上考虑,我的代码考虑了很多情况并进行处理。
代码(Java):
public class Solution {
public int myAtoi(String str) {
String intStr = "";
char[] tempArr = str.toCharArray();
char[] arr = new char[tempArr.length];
int num = 0;
int j = 0;
boolean ok = false;
for (; num < tempArr.length; num++) {
if (ok || tempArr[num] - ' ' != 0) {
ok = true;
arr[j] = tempArr[num];
j++;
}
}
if (arr.length == 0 || !((arr[0] - '0' <= 9 && arr[0] - '0' >= 0) || arr[0] - '-' == 0 || arr[0] - '+' == 0)) return 0;
int i = 0;
if (arr[0] - '+' == 0) i = 1;
for (; i < arr.length; i++) {
if ((arr[i] - '0' <= 9 && arr[i] - '0' >= 0) || (i == 0 && arr[i] - '-' == 0)) {
intStr = intStr + arr[i];
} else break;
}
if (intStr.length() == 0) return 0;
else if (intStr.equals("-")) return 0;
else if (i > 11) return intStr.charAt(0) - '-' == 0 ? -2147483648 : 2147483647;
else if (Long.parseLong(intStr) > 2147483647) return 2147483647;
else if (Long.parseLong(intStr) < -2147483648) return -2147483648;
else return Integer.valueOf(intStr).intValue();
}
}
相关文章
- 金融服务领域的大数据:即时分析
- 影响大数据、机器学习和人工智能未来发展的8个因素
- 从0开始构建一个属于你自己的PHP框架
- 如何将Hadoop集成到工作流程中?这6个优秀实践必看
- SEO公司使用大数据优化其模型的5种方法
- 关于Web Workers你需要了解的七件事
- 深入理解HTTPS原理、过程与实践
- 增强分析:数据和分析的未来
- PHP协程实现过程详解
- AI专家:大数据知识图谱——实战经验总结
- 关于PHP的错误机制总结
- 利用数据分析量化协同过滤算法的两大常见难题
- 怎么做大数据工作流调度系统?大厂架构师一语点破!
- 2019大数据处理必备的十大工具,从Linux到架构师必修
- OpenCV中的KMeans算法介绍与应用
- 教大家如果搭建一套phpstorm+wamp+xdebug调试PHP的环境
- CentOS下三种PHP拓展安装方法
- Go语言HTTP Server源码分析
- Go语言HTTP Server源码分析
- 2017年4月编程语言排行榜:Hack首次进入前五十