leetcode做题记录0008
发布日期:2021-05-07 13:47:44 浏览次数:16 分类:技术文章

本文共 1077 字,大约阅读时间需要 3 分钟。

leetcode 0008

说明

只是为了记录一下,不求多快,也不深究。

会简要描述思路,代码中不写注释。

如碰到不会做的用了别人代码会在博客中标出。

题目描述

在这里插入图片描述

在这里插入图片描述

结果

在这里插入图片描述

思路

就是加一些判断条件,找一个数字子串。

找到开始和结束的地方。

int n = Integer.valueOf(num);用这个函数直接转数字。

加个try{}catch{},越界直接返回那两个边界数字就完事儿了。

代码

class Solution {       public int myAtoi(String str) {   		if(str.length()==0) {   			return 0;		}		int idxStart = 0,idxEnd;		boolean isNegative = false;		boolean hasSign = false;		String s=null;		for(int i=0;i
='0'&&s.charAt(0)<='9')) { return 0; } if(s.charAt(0)=='-') { isNegative = true; hasSign = true; ++idxStart; } if(s.charAt(0)=='+') { ++idxStart; hasSign = true; } if(hasSign&&(s.length()==1||!(s.charAt(1)>='0'&&s.charAt(1)<='9'))) { return 0; } for(idxEnd = idxStart;idxEnd
='0'&&s.charAt(idxEnd)<='9') { ++idxEnd; }else { break; } } String num = s.substring(idxStart, idxEnd); try { int n = Integer.valueOf(num); if(isNegative) { return -n; }else { return n; } }catch(Exception e){ if(isNegative) { return -2147483648; }else { return 2147483647; } } }}
上一篇:leetcode做题记录0009
下一篇:决策树(一)—— 信息熵及衍生概念

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月27日 00时48分24秒