leetcode 8
来源:互联网 发布:淘宝微能量运动旗舰店 编辑:程序博客网 时间:2024/05/29 15:18
leetcode 8 String to Integer (atoi)
这道题最重要的是理解题意
对于我这种只会一些肤浅的java知识的菜鸟,根本不知道atoi是什么(尴尬脸)
atoi:
atoi ( ascii to integer)是把字符串转换成整型数的一个函数。
atoi( ) 函数会扫描参数 nptr字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过isspace( )函数来检测),直到遇上数字或正负符号才开始转换,而再遇到非数字或字符串结束时结束转换,并将结果返回。如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回 0 。
注意:题目中还加了一条,如果超出int型的上下限该输出对应的上限或者下限。
首先理解好题目意思,不要产生误解,这是解好题目的前提。
所以,使用spilt过滤,正则表达式等想法都不对 Σ( ° △ °|||)︴
最后还是逐步处理字符串最实在。注意一些特殊情况:
- “”空串
- “ ”只有空格或Tab的字符串
- “ abc”,“ ab93489”,“ -”,“ -dauhi24”除空格和Tab,只有字母,只有字母数字,只有符号,符号后紧跟字母
- “ -28378abc”,“ -28378abc324”,“ -28378 ”,“ -28378 dua28”符号数字跟字母/字母+其他(数字也没差别)/空格/空格+其他
- “ -0.3”小数
- “2147483648”超上限
- “-2147483649”超下限
“004”数字前有0
最后,附代码:
public int myAtoi(String str) { long result = 0;//用于判断是否超出上下限 int sign = 1; int index = 0; if(str.length()==0) return 0; // if(str.charAt(index)==' ') index++;这样的写法只能去掉一个空格 while(str.charAt(index)==' '||str.charAt(index)==' ') { if(index<str.length()-1) index++;//-1是必要的,解决全空格全Tab问题 else break; } if(str.charAt(index)=='+'||str.charAt(index)=='-'){ sign = str.charAt(index)=='+'?1:-1; index++; } while(index<str.length()){ int digit = str.charAt(index) - '0'; if(digit>9||digit<0) break; result = result*10 + digit; if(result*sign>Integer.MAX_VALUE||result*sign<Integer.MIN_VALUE){ return result*sign>0?Integer.MAX_VALUE:Integer.MIN_VALUE; } index++; } return (int)result*sign;}
0 0
- leetcode 8
- leetcode-8
- leetcode 8
- Leetcode--8
- LeetCode(8)
- leetcode 8
- LeetCode(8)StringToInteger
- [LeetCode] Reverse Integer [8]
- Leetcode--easy系列8
- leetcode #8 atoi
- leetcode第8题
- Leetcode(8)-medium2
- leetcode 8 atoi
- Leetcode no. 8
- leetcode试题总结<8>
- 【Leetcode】UTF-8 Validation
- LeetCode OJ(8)
- Leetcode #8 Solution
- 一次spark任务优化
- CGLib动态代理原理及实现
- description方法
- 深度增强学习David Silver(一)——介绍
- maven阿里云中央仓库
- leetcode 8
- 《google软件测试之道》读书笔记
- Category添加weak属性的精简版本
- bzoj 2432: [Noi2011]兔农 (数论+矩阵乘法)
- JFinal
- 旋转矩阵与四元数
- 实现三个并排div,两边固定宽度,中间自适应的四个方法
- tcpdump命令
- hibernate的方法运用