String to Integer (atoi) 转换string为整数@LeetCode

低功耗 AI 人体存在检测系统:智能照明与安防的高效解决方案 低功耗 AI 人体存在检测系统通过 “ESP32-C3 主控 + HX7110 AI 模块” 的硬件组合,搭配双重检测算法与深度睡眠机制,既解决了传统检测方案的误报问题,又满足了长时间低功耗运行需求。系统接线简单、代码可直接移植,可快速集成到智能照明、安防监控等物联网设备中,具备广泛的应用前景。 阅读详情

思路:

处理whitespace和符号位,然后边遍历边累计和



挺tricky的一题,这题我没有用正常的方法来做,用了挺邪恶的方法:

1 用正则表达式过滤掉前面的whitespace

2 用Long去parseLong,这里还遇到奇怪的问题,当parseLong传+号时,在本机跑没问题,一到OJ上就会Runtime Exception!

3 用了Exception做检查


这题肯定有比较正常的做法,但也许这是最直观的方法了


附带几个做Regex比较有用的网站:

http://www.freeformatter.com/java-dotnet-escape.html

http://regexpal.com/

http://www.regexplanet.com/advanced/java/index.html


package Level2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * String to Integer (atoi)
 * 
 * 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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
 * 
 */
public class S8 {

	public static void main(String[] args) {
//		String str = "  sf  -2147483648   asfasdf";
//		String str = "      321f";
//		String str = " -0012a42";
//		String str = " 10522545459";
//		String str = "-abc";
		String str = "+1";
		System.out.println(atoi(str));
	}
	
	public static int atoi(String str) {
		
		if(str==null || str.length()==0){
			return 0;
		}
		
		// 找到第一个非whitespace的
		Pattern p = Pattern.compile( "([\\S]\\d*)" );
		Matcher m = p.matcher(str);
		String trim = str;
		if( m.find() ){
			trim = m.group();
		}
		
		// 判断第一个符号
		char c = trim.charAt(0);
		if(c!='-' && c!='+' && !Character.isDigit(c)){
			return 0;
		}
		// 很奇怪,必须把+号过滤掉,否则OJ返回Runtime Error
		if(c == '+'){
			trim = trim.substring(1);
		}
		
		int ret = 0;
		long temp = 0;
		// tricky,用Long去parse,检查Exception
		try{
			temp = Long.parseLong(trim);
		}catch (Exception e) {
			return 0;
		}
				
        if (temp > Integer.MAX_VALUE){
        	ret = Integer.MAX_VALUE;           
        }
        else if (temp < Integer.MIN_VALUE){
        	ret = Integer.MIN_VALUE;
        }
        else {
        	ret = (int) temp;
        }
		return ret;
    }

}


Second try:

这次是非常正统的做法,肯定挑不出岔。

/*
	 http://www.cnblogs.com/freeneng/archive/2013/04/15/3022107.html
	 Analysis:

Possible input cases:

1. "", empty string

2. "123", simple valid string

3. "+123", valid string with '+' sign

4. "-123", valid string with '-' sign

5. " 123abc ", string with space and other characters

6. "abc123", invalid input string

7. "33333333333333", "-3333333333333", invalid overflow string

According to those given cases, we should follow the steps listed below:

1. check whether the string is empty, define what to return if the string is empty; if it's empty, return directly

2. trim the spaces of the string both at the head and the end

3. judge whether the first character is '+' or '-', by default no either of them are positive num

4. start from the first position, continue convert until meeting the end of the string or a non-numeric character

5. judge whether the result overflows, if overflow, return the MAX_VALUE or MIN_VALUE, else return the result
	 */
	public static int atoi(String str){
		if(str == null || str.length()==0){
			return 0;
		}
		int pos = 0, ret = 0;
		long val = 0L;
		char flag = '+';
		
		str = str.trim();		// 过滤掉前面的whitespace
		if(str.charAt(0)=='+' || str.charAt(0)=='-'){		// 获得符号
			pos++;
			flag = str.charAt(0);
		}
		
		while(pos<str.length() && Character.isDigit(str.charAt(pos))){
			val = val*10 + (str.charAt(pos)-'0');	// 累积和
			pos++;
		}
		
		if(flag == '-'){		// 负号处理
			val = -val;
		}
		
		if(val > Integer.MAX_VALUE){
			ret = Integer.MAX_VALUE;
		}else if(val < Integer.MIN_VALUE){
			ret = Integer.MIN_VALUE;
		}else{
			ret = (int)val;
		}
		return ret;
	}


迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM) 迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM) 立即下载

相关推荐

避坑指南:CesiumLab+ENVI处理Sentinel-2影像数据的完整流程

本文提供了一份详细的避坑指南,完整介绍了如何利用CesiumLab和ENVI工具链,将Sentinel-2卫星影像处理成可供Cesium三维地球引擎加载的离线瓦片数据。内容涵盖数据获取、SNAP预处理、ENVI影像增强合成以及CesiumLab切片配置等全流程实战步骤与关键参数优化,旨在帮助工程师高效构建自主可控的高精度离线地图服务。

weixin_29248653的博客 288

StringUtils函数全集

StringUtils中方法的操作对象是java.lang.String类型的对象,是JDK提供的String类型操作方法的补充,并且是null安全的(即如果输入参数String为null则不会抛出NullPointerException,而是做了相应处理,例如,如果输入为null则返回也是null等,具体可以查看源代码)。 除了构造器,StringUtils中一共有130多个方法,并且都是...

yyyangjun的专栏 1024

聚类模型-层次聚类

聚类模型 1、层次聚类 2、原型聚类-K-means 3、模型聚类-GMM 4、EM算法-LDA主题模型 5、密度聚类-DBSCAN 6、图聚类-谱聚类 一、层次聚类 一、聚类理论 ​ 一般来说,聚类是在训练样本的标签信息不知的情况下,学习样本内在的性质和规律,将有限的集合划分成ccc类。根据“方以类聚,物以群分”的思想,类内对象尽可能的相似,...

myazi 6502

druid报错StringUtil stringToInteger fail,string={datasourceId}

[WARN ]2018-06-29 09:45:25,361 - com.alibaba.druid.util.StringUtils -stringToInteger fail,string={datasourceId}java.lang.NumberFormatException: For input string: "%7BdatasourceId%7D"    at java.lang.N...

qq_38706757的博客 1436

别再手动抄表了!用MCGS触摸屏自动存数据到U盘,5分钟搞定报表导出

本文详细介绍了如何利用MCGS触摸屏实现工业数据自动记录与U盘导出,彻底告别传统手动抄表方式。通过昆仑通态MCGS系统,可构建零误差自动化报表系统,实现实时数据采集、双重备份及标准CSV格式导出,大幅提升数据准确性和工作效率。

weixin_30872157的博客 791

软件自动化测试脚本如何编写,编写自动化测试脚本的几点注意事项

我们需要自动化测试脚本的原因:1、验收测试是一项非常复杂和费力的被用来确保软件质量的环节。它的目的就是使软件能得到充分运行并且能使其符合原始需求。2、测试的目的无非就是满足了两个结果:测试通过或测试不通过。为了能实现每个测试结果,必须要明确每个测试用例。并且对于整个系统而言在合同中必须定义测试用例的失败标准,而且这个失败标准数必须是可接受的。3、测试用例的通过条件必须有一个清晰的标准,标准可以被定...

weixin_39575775的博客 2251

String to Integer (atoi)

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 ca

xinzhongtianxia的博客 301

基于Pixi.js的Live2D看板娘离线加载实战指南

本文详细介绍了基于Pixi.js实现Live2D看板娘离线加载的完整方案,涵盖环境搭建、模型加载、交互功能实现及常见问题解决。通过Pixi.js的硬件加速优势,开发者可在Web和Electron项目中无缝集成离线运行的Live2D模型,提升用户体验并避免网络依赖问题。

weixin_29001423的博客 343

LeetCode(8):字符串转换整数 (atoi) String to Integer(Java)

2019.4.15 这道题手撕字符串转换函数。 难点在于对特殊情况的判断,比如符号,比如大数等等。需要记测试用例和边界条件。 传送门:字符串转换整数 (atoi) Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as ne...

NJU_ChopinXBP的博客 433

19、英国模式:银行体系的演变与现代金融架构

本文深入探讨了英国银行体系从专业化向全能银行的演变过程,分析了自律监管模式的优劣,并解析了围栏制度对金融稳定的影响。同时,文章还介绍了信用合作社、建筑协会和投资银行的角色与转型,全面展示了英国金融体系的多样性与复杂性,以及其在全球金融市场中的重要作用。

embedding5hiker的博客 104

Qwen2.5-VL多模态微调超参数深度解析(上):训练流程与优化策略的量化机制分析

上篇文章通过系统化的对比实验,回答了多模态微调中的三个基础问题:“选什么方法”(LoRA/Full/Freeze/OFT对比)、“用什么配置”(60+组超参数组合)、“达到什么效果”(ROUGE-L/BLEU-4指标)。这些结果为后续工作奠定了实验基线,但也留下了更深层的疑问:为何相同方法在不同数据集上表现迥异?为何某些超参数的微小调整会引发性能剧变?如何在未见过的任务上快速找到最优配置?本文是对前文实验数据的二次挖掘与机理解析。我们将关注点从"做了什么实验"转移到"实验揭示了什么规律",实验视角从"结果对

羊城迷鹿的博客 1004

LeetCode 8 String to Integer (atoi)

String to Integer (atoi) 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

gx262091291的专栏 330

RK3568-适配phy芯片ip101gri

复位时间查阅数据手册。

Paper_Love的博客 2643

@LeetCode字符串转换整数(atoi)--String to Integer(atoi)[C++]

@LeetCode字符串转换整数--String to Integer[C++]问题描述解决方法及复杂度问题程序实现 问题描述 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 说明: 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,231−1][-2^{31},2^{31}-1][−231,231−1]。如果数值超过这个范围,请返回 INT_MAX(23...

乾小二 272

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

atoi和itoa函数及负数转正数时溢出问题

首先贴出c函数库里的atoi函数, 其实是atol函数, 因为atoi调用了atol函数. 函数很简单,相信大家一看就懂. isspace函数是判断传入字符是否为空白符, 空白符指空格, 水平制表, 垂直制表, 换页, 回车和换行符. 函数首先跳过空白字符, 之后判断正负号, 判断完正负号后判断字符是否为数字, 如果是则循环, 直到遇到非数字为止, 如果第一次循环就不是数字则直接返回 tota

u012410778的专栏 8036

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

LeetCode 8 String to Integer (atoi)(转换到整型)

翻译 实现“atoi”将字符串转换成整型数。 提示:仔细考虑所有可能的输入。如你想要挑战,请不要参阅下面并问问自己都有哪些可能的输入请看。 说明:模糊的指定(没有给定的输入规格)就是为了这个问题。你负责收集所有可能的输入。 atoi的要求: 函数首先放弃尽可能多的空字符直到找到一个非空白字符。然后从这个字符开始,带上可选的...

weixin_34217711的博客 112

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Leetcode 解题 8 String to Integer (atoi)

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this...

mai_86的博客 243

LeetCode 8:String to Integer (atoi)

题目的大概意思是:按照atoi函数的转换原则,将输入的字符串转换成整型数。其实就是自行实现atoi函数。这道题难度等级:简单需要注意的是以下几点:但是怎么觉得不止这几种情况啊,这些情况我都考虑且避免了。还是AC不掉,暂时没有找到一个详细的转换原则。网上找到的代码如下:class Solution { public: int myAtoi(string str) { ...

momo_mo520的博客 177

8. String to Integer (atoi)(Leetcode每日一题-2020.04.03)

Problem Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting f...

Bryan要加油 467

GPT-4技术解析:从Transformer架构到三阶段训练与实战应用

自然语言处理领域的核心突破源于Transformer架构及其自注意力机制,该机制通过并行计算实现了对长序列数据的高效建模。基于此构建的大规模语言模型,通过海量数据预训练掌握了语言的统计规律与知识表示。在工程实践中,结合监督微调与基于人类反馈的强化学习等技术,模型得以与人类价值观对齐并遵循复杂指令。这类技术已广泛应用于智能对话、代码生成与多模态内容创作等场景。以GPT-4为代表的先进模型,正是通过极致化模型规模、训练范式与架构创新,将语言模型的上下文理解、逻辑推理及多模态处理能力推向新高度,成为当前人工智能工

weixin_30608503的博客 719

LeetCode 8. String to Integer (atoi)简单易懂的解法

//Author: yqtao //Email : yqtao@whu.edu.cn //Date :2016.7.5 /************************************** * Implement atoi to convert a string to an integer. * 实现一个字符串到数字的转换 ******************************/

yqtao的博客 617

Implement atoi to convert a string to an integer.

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 ca

Daisy_HJL的博客 565

字符串转换整数 (string-to-integer-atoi)

文章目录字符串转换整数 (string-to-integer-atoi)思考问题1 ,怎么从字符串拿到一位数字问题2,只有数字的字符串转成整数问题3,怎么判断正负问题4,开始数字在哪个位置代码 字符串转换整数 (string-to-integer-atoi) 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。...

mirana的专栏 529

String to Integer (atoi)问题及解法

问题描述: 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 i

刘天的博客 353

【leetcode】8. String to Integer (atoi)(从string中按照规则提取int)

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from thi...

qq_37355731的博客 215

LeetCode 8: String to Integer (atoi)

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this...

颹蕭蕭 1512
上一篇: 软件工程师薪酬最高的25家公司!!!
下一篇: Add Two Numbers 把两个以链表形式表示的数相加 @LeetCode
chiiis
博客等级 码龄14年 422粉丝 429原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值