当前位置:网站首页>字符串转换整数 (atoi)
字符串转换整数 (atoi)
2022-08-09 12:00:00 【爱敲代码的Harrison】
题目
力扣链接:字符串转换整数 (atoi)
代码
package com.lt.tiq01;
/** * @author Harrison * @create 2022-06-26-11:20 * @motto 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。 */
public class P006_StringToIntegerAtoi {
public int myAtoi(String s) {
if(s==null || s.equals("")){
return 0;
}
// trim()把字符串的空格去掉,一个系统函数
s=removeHeadZero(s.trim());
if(s==null || s.equals("")){
return 0;
}
char[] str=s.toCharArray();
if(!isValid(str)){
return 0;
}
// str 是符合日常书写的,正经整数形式
// 为什么一定要转成负数的形式接着?
// -2147483648
// 2147483647
// 因为负数的绝对值比正数的绝对值大1,如果硬要拿正数接着
// 那么字符串"2147483648"就没法转换了,但其实按要求应转换为系统最大2147483647
// 因为是用负数的形式接着,所以不会溢出
boolean posi=str[0]=='-'?false:true;
int minq=Integer.MIN_VALUE/10;
int minr=Integer.MIN_VALUE%10;
int res=0;
int cur=0;
for(int i=(str[0]=='-' || str[0]=='+')?1:0; i<str.length; i++){
cur='0'-str[i];
if(res<minq || (res==minq && cur<minr)){
// 正数溢出返回系统最大,负数溢出返回系统最小
return posi?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
res=res*10+cur;
}
// "-2147483648" -> -2147483648
// "2147483647" -> 2147483647
// res是用负数形式表达的
// "2147483648" -> 2147483647
// 下面if的情况,res是正数的形式,但却是系统最小,不会溢出,因为使用负数形式接着的
// 这种情况下转成系统最大
if(posi && res==Integer.MIN_VALUE){
return Integer.MAX_VALUE;
}
return posi?-res:res;
}
public static String removeHeadZero(String str){
boolean r=(str.startsWith("+") || str.startsWith("-"));
// 如果原字符串第一个字符包含'+'或'-',那就从第二个字符开始找第一个不是'0'的字符
int s=r?1:0;
for(; s<str.length(); s++){
if(str.charAt(s)!=0){
// 找到第一个不是字符'0'的位置
break;
}
}
// s 到了第一个不是'0'字符的位置
int e=-1;
// 左<-右(从右往左找第一个不是数字字符的位置)
for(int i=str.length()-1; i>=(r?1:0); i--){
if(str.charAt(i)<'0' || str.charAt(i)>'9'){
e=i;
}
}
// e 到了最左的 不是数字字符的位置
// substring(s,e) 左闭右开[s,e)
// 如果e==-1,说明s后面都是数字字符
// 再加上第一个字符'+'或者'-',如果有的话
return (r?String.valueOf(str.charAt(0)):"")+str.substring(s,e==-1?str.length():e);
}
// isValid() 检查是否是有效的整数
public static boolean isValid(char[] chas){
if(chas[0]!='-' && chas[0]!='+' && (chas[0]<'0' || chas[0]>'9')){
return false;
}
if((chas[0]=='-' || chas[0]=='+') && chas.length==1){
return false;
}
// 上面两个if没中,只剩下三张情况
// 0 +... -... num
// 0位置字符是'+',后面是数字字符
// 0位置字符是'-',后面是数字字符
// 0位置就是数字字符,后面也是
// 然后接着从1位置开始检查,如果中间有任何不是数字字符,直接return false
for(int i=1; i<chas.length; i++){
if(chas[i]<'0' || chas[i]>'9'){
return false;
}
}
// 经过上面的层层过滤,剩下的字符串一定是符合我们日常书写的,正经的整数形式
return true;
}
}
边栏推荐
- AQS同步组件-FutureTask解析和用例
- AQS Synchronization Component - FutureTask Analysis and Use Cases
- 00后写个暑假作业,被监控成这笔样
- 实验记录:搭建网络过程
- Web console control edit box
- 防止数据冒用的方法
- 阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端
- Adalvo收购其首个品牌产品Onsolis
- ABAP interview questions: how to use the System CALL interface of the ABAP programming language, direct execution ABAP server operating System's shell command?
- GET请求和POST请求区别
猜你喜欢

告别手摇织布机的AI时代

一甲子,正青春,CCF创建六十周年庆典在苏州举行

00后写个暑假作业,被监控成这笔样

LeetCode热题(11.合并两个有序链表)
![[Interview high-frequency questions] Linked list high-frequency questions that can be gradually optimized](/img/a4/97ce319e08dee8171de76beffe1d7b.png)
[Interview high-frequency questions] Linked list high-frequency questions that can be gradually optimized

ThreadLocal的简单理解

用皮肤“听”音乐,网友戴上这款装备听音乐会:仿佛住在钢琴里

【微服务~远程调用】整合RestTemplate、WebClient、Feign

阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端

ABAP interview questions: how to use the System CALL interface of the ABAP programming language, direct execution ABAP server operating System's shell command?
随机推荐
鹅厂机器狗花式穿越10m梅花桩:前空翻、单桩跳、起身作揖...全程不打一个趔趄...
Ways to prevent data fraud
金融业“限薪令”出台/ 软银出售过半阿里持仓/ DeepMind新实验室成立... 今日更多新鲜事在此...
WeChat side: what is consistent hashing, usage scenarios, and what problems does it solve?
PM2 configuration file
electron 应用开发优秀实践
Blazor Server (9) from scratch -- modify Layout
WeChat Mini Program Payment and Refund Overall Process
IDEA close/open reference prompt Usages
The latest interview summary in 20022 brought by Ali senior engineer is too fragrant
shell脚本------函数的格式,传参,变量,递归,数组
在北极都可以穿短袖了,温度飙升至32.5℃
go基础之web获取参数
【无标题】
程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
MySQL中的锁
Two minutes recording can pass by second language!The volcano how to practice and become voice tone reproduction technology?
网页控制台控制编辑框
LeetCode #101. 对称二叉树
苹果Meta都在冲的Pancake技术,中国VR团队YVR竟抢先交出产品答卷