leetcode刷题8. String to Integer (atoi)
来源:互联网 发布:疯狂联盟座狼升级数据 编辑:程序博客网 时间:2024/05/17 20:34
题目的意思是这样的:仿照c语言的atoi函数,写一个函数,输入一个字符串,返回一个int类型的变量。
百度百科一下atoi函数:对一个字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零。
结合百度百科的atoi函数的功能并结合题目的补充说明,算法分为以下几个步骤:
(1)获取str的第一个非空字符。 如果没有获取到任何非空字符,返回0。
否则进入(2)。
(2)获取第一个非空字符, 如果字符为数字0到9,开始计算,并进入(3)。
如果字符为'+',进入(3)。
如果字符为'-',设置一个标记,表示以后的“计算”都是负数计算,进入(3)。
否则返回0。
(3)获取str的下一个字符。如果是这个字符数字'0'到’9’,进行计算,如果不越界,返回(3)。
如果越界,返回Integer的maxvalue或minvalue。
否则返回0。
代码如下:
public class Solution { public int myAtoi(String str) { if(str.length()==0) return 0; char[] strs = str.toCharArray(); long sum = 0; int i = 0; boolean flag = false; while(strs[i]==' ') i++; if(strs[i]=='+') { i++; } else{ if(strs[i]=='-') { i++; flag = true; } } for(;i<strs.length;i++) { if(strs[i]>='0'&&strs[i]<='9') { if(flag) { sum = sum*10-(strs[i]-'0'); if(sum<Integer.MIN_VALUE) return Integer.MIN_VALUE; } else { sum = sum*10+(strs[i]-'0'); if(sum>Integer.MAX_VALUE) return Integer.MAX_VALUE; } } else break; } return (int)(sum); }}
0 0
- leetcode刷题8. 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)
- Leetcode ☞ 8. String to Integer (atoi)
- 8. String to Integer (atoi) ---Leetcode
- leetcode 8. String to Integer (atoi)
- 电话监听器
- lightoj 1198 - Karate Competition 【贪心】
- IOS App常用界面结构解析,让开发更简单
- SAR成像学习(三)距离方向成像matlab代码解析 1
- 四 单例模式
- leetcode刷题8. String to Integer (atoi)
- ThreadLocal类源码解析
- java---序列六(合并流)SequenceInputStream ——对多个流进行合并
- 致自己
- 开发工具
- js中call与apply用法
- 深入理解JVM(九)——类加载的过程
- leetcode 93. Restore IP Addresses
- lightoj 1328 - A Gift from the Setter 【数学】