8,String to Integer (atoi)
来源:互联网 发布:mac玩使命召唤 编辑:程序博客网 时间:2024/06/06 04:10
Implement atoi to convert a string to an integer.//实现atoi函数,实现字符串到整形的转换
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.
题目分析:这是一道算法思想很简单的题目,属于细节题,其中藏着很多陷阱。
1.数字前面有空格 如s=“ 123456”
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0 如s=“ b1234” ,s=“ ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“ 12a12” , s=“ 123 123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648 超过了正数的输出2147483647
程序如下:
public class Solution { public int atoi(String str){ //考虑""的情况 if(str.length()==0) return 0; //结果 int result=0; //符号 int sign=1; int i=0; //去除前面的空格 while(str.charAt(i)==' ') ++i; //判断符号 if(str.charAt(i)=='-') { sign=-1; ++i; } else if(str.charAt(i)=='+') { sign=1; ++i; } for(;i<str.length();++i) { if('0'<=str.charAt(i)&&str.charAt(i)<='9') { //判断是否溢出 if(result>Integer.MAX_VALUE/10|| (result==Integer.MAX_VALUE/10&& str.charAt(i)-'0'>Integer.MAX_VALUE%10)) return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE; result*=10; result+=str.charAt(i)-'0'; } else return result*sign; } return result*sign; }}
如" +0012 123" 正确输出为12
"+-12" 正确输出为0,因为+为开始,-为结束,中间只有0的结果
- 8、String to Integer (atoi)
- 8,String to Integer (atoi)
- 8 String to Integer (atoi)
- 8 String to Integer (atoi)
- #8 String to Integer (atoi)
- 8String to Integer (atoi)
- 8 String to Integer (atoi)
- 8 - String to Integer (atoi)
- [8]String to Integer (atoi)
- 8、String to Integer (atoi)
- 【8】String to Integer (atoi)
- 8String to Integer (atoi)
- 8 String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- Magento1.9.1.0重要改进之一--邮件异步队列发送
- eclipse中jsp页面.不出现自动提示
- 浅谈 upstart 和 孤儿进程问题!!!
- *LeetCode-Maximum Subarray
- ZOJ - 3816 Generalized Palindromic Number dfs+数位DP+贪心
- 8,String to Integer (atoi)
- 糗事百科爬虫
- 恒生2015实习小结
- OpenMP VS2010 环境配置
- hdu 1498 50 years, 50 colors 二分匹配
- 几个常用的操作系统进程调度算法
- 机器学习中的相似性度量
- list-style 用法 ul ol
- 顾不及跬步,无以至千里