8. String to Integer
2016-03-14 10:05
337 查看
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.
将一个字符串转化为 int 型。
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.
将一个字符串转化为 int 型。
1. null or empty string 2. white spaces 3. +/- sign 4. calculate real value 5. handle min & max
public int atoi(String str) { if (str == null || str.length() < 1) return 0; // trim white spaces str = str.trim(); char flag = '+'; // check negative or positive int i = 0; if (str.charAt(0) == '-') { flag = '-'; i++; } else if (str.charAt(0) == '+') { i++; } // use double to store result double result = 0; // calculate value while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { result = result * 10 + (str.charAt(i) - '0'); i++; } if (flag == '-') result = -result; // handle max and min if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int) result; }
相关文章推荐
- 使用AVFoundation生成缩略图
- 【转】JVM运行原理及JVM中的Stack和Heap的实现过程
- iOS开发进阶之 UIWebView
- Quake3游戏引擎中平方根相关算法
- 文件属性之stat(),fstat(),lstat(),chown(),fchown(),lchown()函数
- rename(),unlink(),getcwd(),chdir(),opendir(),readdir(),closedir()函数
- java系统高并发解决方案(转载)
- java程序设计基础_陈国君版第五版_第十一章习题
- getpwuid()函数,getpgrgid()函数()
- fork() 函数,vfork()函数
- 限制
- 无处不在的培训
- 北大生弑母,可怜之人必有可恨之处
- 小李拿奥斯卡奖之热点营销
- 房价又涨了
- 扁平化之管理
- 你真的会复盘吗?(2)
- 复盘
- 拜神
- 求存与求真