LeetCode #8 String to Integer (atoi) 字符串转数字 解题小节
2016-03-11 23:30
543 查看
1 原题
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
2 题目理解
这题的意思是,给定一个用String表示的数字,然后需要你转化为一个真正的int呢。Leetcode标记的难度是Easy,但是我觉得这道题陷阱很多,要注意到很多很多特别的地方,我就这么提几个:
0、我做的时候给定的String一定是合法的数字,这点很重要,因为我往后刷遇到过类似问题,这边给定的是合法的,所以部分处理就很简单了,特别是空格。
1、注意前后的空格,输入的数字可能会留空,所以往前往后都需要去空格。
2、需要考虑正负号,这个是合法的
3、注意int的最大值和最小值的绝对值大小不一样,所以如果在计算的时候是暂时抛弃了符号,一位一位的前进的,需要特别注意这个问题。
4、注意不要溢出
总之流程就是:
1、去除空格
2、检查是否正反符号
3、转换数字整体,并时刻检查是否溢出,关于溢出的问题的解决,可以看我前面的博客,这里我选用了long解决
3 AC解 Java
public class Solution { /** * 倘若某个数超过了2147483647则会变为负数,反过来一样*/ public int myAtoi(String str) { if(str.equals("")) return 0; char chars[]=str.toCharArray(); long result=0,maxs=Integer.MAX_VALUE,mins=-1*(long)Integer.MIN_VALUE; int i=0,flag=1; while(chars[i]==' '){ i++; } if(chars[i]=='-'){ flag=-1; i++; } else if(chars[i]=='+'){ flag=1; i++; } while(i<str.length()){ if(chars[i]==' ') return (int)result*flag; if( chars[i]>'9' || chars[i]<'0' ) return (int)result*flag; result=result*10+(chars[i++]-'0'); if(flag==1 && result>maxs ){ return (int)maxs*flag; } if(flag==-1 && result>mins ){ return (int)mins*flag; } } return (int)result*flag; } }
相关文章推荐
- 【POJ 3083】Children of the Candy Corn
- 2016第10周五
- 用UIPickerView来显示省和市
- Codis作者黄东旭细说分布式Redis架构设计和踩过的那些坑们
- c++ 深浅拷贝(传统写法 现代写法)
- BZOJ-3282 Tree Link-Cut-Tree(似乎树链剖分亦可)
- backbone官方Todo示例分解学习
- 学生信息管理系统1.0
- BZOJ-3282 Tree Link-Cut-Tree(似乎树链剖分亦可)
- [转]World Wind Java开发之四——搭建本地WMS服务器
- c++ 深浅拷贝(传统写法 现代写法)
- HDU 2489 Minimal Ratio Tree(dfs+最小生成树)
- [POJ2104]K-th Number(静态主席树)
- Manacher 线性时间求最长回文串
- 用 eric6 与 PyQt5 实现python的极速GUI编程(系列01)--Hello world!
- Android Stutio 提示错误:Plugin is too old, please update to a more recent version......的解决办法
- 本地gradle的一些命令
- 解决百度云下载速度缓慢问题
- Linux 字符设备驱动开发基础(五)—— ioremap() 函数解析
- python 作用域