LeetCode 之 String to Integer (atoi)
来源:互联网 发布:中学生学编程学什么好 编辑:程序博客网 时间:2024/05/17 05:53
题目链接:String to Integer (atoi)
这道题目的关键的地方是要考虑到很多中不同的情况。
1、去除字符串前的空格;
2、除空格以外的第一个字符需要是+/-或者有效的数字0-9,;
3、如果第一个字符为+/-,其后紧接着的必须为有效数字直到遇到非数字即可;
4、如果第一个字符不为运算符或者紧接着运算符的不是有效的数字,则转换无效,返回0;
5、如果第一个字符为“-”,则需要将转换后的正数转为负数;
6、要考虑转换后的数值范围,如果正确值超出了可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648);
代码如下:
class Solution { public int myAtoi(String str) { int i = 0; if(str.length()==0) return 0; str = str.trim(); \\去掉字符串头尾的空格 double re = 0; int flag = 0; //首先判断第一个非空字符是否为“+/-” if(str.charAt(0)=='+') i++; if(str.charAt(0)=='-'){ flag = 1; i++; } //循环遍历,并将其转换为对应的数值,知道遇到第一个非数字字符或者超过字符串的范围 while(i<str.length()&&str.charAt(i)>='0'&&str.charAt(i)<='9'){ int tmp = str.charAt(i) - '0'; re = re*10 + tmp; i++; } //如果运算符号为“-”,则取反 if (flag == 1) re = -re; //判断数值的范围是否超过int类型 if (re > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (re < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int) re; } }
阅读全文
0 0
- leetCode 之 String to Integer (atoi)
- leetcode 之 String to Integer (atoi)
- leetcode 之 String to Integer (atoi)
- leetcode之String to Integer (atoi)
- LeetCode之String to Integer(atoi)
- Leetcode之String to Integer (atoi)
- 【Leetcode】之String to Integer (atoi)
- LeetCode之8----String to Integer (atoi)
- LeetCode 之 String to Integer (atoi)
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- 剑指offer学习笔记-2.2 编程语言(1)
- 高数 02.01导数的概念
- matplotlib 画图
- 【转载】从单体架构迁移到微服务,8个关键的思考、实践和经验
- Java POI导出Excel
- LeetCode 之 String to Integer (atoi)
- ./configure,make,make install的作用
- 实现collectionview加载到tableview的tableFooterView上一起滑动(类似淘宝购物车)--通过添加观察者实现
- 前台一些问题样式,显示问题
- TensorFlow使用的一个小案例
- 【精】客户端(iOS、Android)/Server,APP内部的通信协议,跨平台方案
- Mybatis系列---强大的动态SQL
- 导航栏二级悬浮菜单样式
- 数据库范式