当前位置:网站首页>实现字符串转换为整数(atoi)
实现字符串转换为整数(atoi)
2022-08-08 06:27:00 【写做四月一日的四月一日】
实现要求:
读入字符串并丢弃无用的前导空格
检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终结果是负数还是正数。 如果两者都不存在,则假定结果为正。
读入下一个字符,直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。
将前面步骤读入的这些数字转换为整数(即,"123" -> 123, "0032" -> 32)。如果没有读入数字,则整数为 0 。必要时更改符号(从步骤 2 开始)。
如果整数数超过 32 位有符号整数范围 [−231, 231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被固定为 −231 ,大于 231 − 1 的整数应该被固定为 231 − 1 。
返回整数作为最终结果。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-integer-atoi
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题
流程
class Solution {
//界限值
public static final int INT_MAX = 0x7FFFFFFF;
public static final int INT_MIN = 0x80000000;
public int myAtoi(String str) {
//空串判断
if(null == str){
return 0;
}
str = str.trim();
int length = str.length();
if(0 == length){
return 0;
}
char cur = 0;
boolean isPositive = true;
int res = 0;
for (int index = 0; index < length; index++){
cur = str.charAt(index);
//是数据就添加在末尾
if(cur >= '0' && cur <= '9'){
//超界就返回界限值
if(index > 8 && (res > INT_MAX / 10 || (cur >= '8' && res == INT_MAX / 10))){
return isPositive?INT_MAX:INT_MIN;
}
res = res * 10 + cur - '0';
//不是数据
}else{
//符号只有第一位是有用的
if (0 == index){
if (cur == '-'){
isPositive = false;
}else if(cur != '+'){//不是正负号就是无效的字符
break;
}
}else {
break;
}
}
}
return isPositive?res:-res;
}
}
边栏推荐
- 带头双向循环链表的增删查改
- Leetcode题目分享以及讲解
- Problems when signed and unsigned numbers are involved in operations
- NVIDIA CUDA Highly Parallel Processor Programming (VII): Parallel Mode: Prefix and
- Problem solving about Unity's button event response error triggering UI events
- 【图形学】01 数学部分(一、集合和三角函数)
- Binary tree traversal and method
- acwing 第63场周赛【2022.08.06】
- 神经网络的图像识别技术,神经网络的层数怎么看
- NVIDIA CUDA 高度并行处理器编程(六):并行模式:卷积
猜你喜欢
Makefile文件的编写(实例详解)
C language judges the problem of big and small endian storage
P19 美颜相机的实现——基础铺垫1
NVIDIA CUDA 高度并行处理器编程(九):并行模式:稀疏矩阵-向量乘法
[Unity] C#使用委托事件与字典实现unity消息中心(观察者模式)
线程P01——进程 并发 并行 线程的使用
【图形学】01 数学部分(一、集合和三角函数)
Unity_预制体批量编辑器
NVIDIA CUDA Highly Parallel Processor Programming (8): Parallel Mode: Histogram Calculation
模块及模块导入
随机推荐
Unity_雷达图(属性图)+ UI动画
Unity3D物体上下左右旋转(不受物体自身坐标轴影响)
计算机网络 | 03.[HTTP篇] HTTP缓存技术
Unity HDRP中代码动态修改天空盒以及其他环境参数
如何规范的开发项目
leetcode每日一题8.6(持续更新)
Problem solving about Unity's button event response error triggering UI events
datetime模块,os模块,sys模块,json模块
二叉树的创建及遍历方法
模块及模块导入
[Unity] C#使用委托事件与字典实现unity消息中心(观察者模式)
Stack queue OJ question sharing and explanation
ExecutionEngineException: String conversion error: Illegal byte sequence encounted in the input.
Unity 本地 IIS 服务搭建之文件夹权限配置
NVIDIA CUDA 高度并行处理器编程(七):并行模式:前缀和
Unity_圆环滑动条(圆形、弧形滑动条)
P20 美颜相机的实现——基础铺垫2
Unity_常用数据分析总结:折线图、条形图(柱状图)、扇形图(饼状图)、雷达图(属性图)
网络开发相关
[Unity] GPU动画实现(二)——网格合并