leetcode之路008 String to Integer (atoi)
来源:互联网 发布:淘宝的旗舰店可信吗 编辑:程序博客网 时间:2024/04/30 01:45
题目大意:实现atoi的功能,把一个字符串转化为整数。
首先的考虑所有的情况,有以下:
1、字符串为空,返回0;
2、字符串中含有‘ ’空格字符,则需要跳过所有空格;
3、考虑符号问题,‘-’和‘+’,最开始自己就没想到‘+’也要考虑;
4、然后必须为数字0-9,如果不为数字,则返回前面已经确定的值。例:“-123a87”,返回的是-123,而不是直接返回错误的值,这这也是最开始完全没想到的,以为直接返回0即可。
5、超出范围问题,超过INT_MAX则返回INT_MAX,小于INT_MIN则返回INT_MIN。刚开始想到要考虑此问题,但以为是返回0,因为也出错。
看似简单的一个题,需要考虑的情况太多,很容易出错,这也是此题ac率只有12%的原因,但题目不说清楚各种情况的返回值值得吐槽。
下面是ac的代码,时间12ms:
class Solution {public: int myAtoi(string str) {int flag=0;long long resu=0;int j=0;if(str.length()==0)return 0;while(str[j]==' ')++j;str=str.substr(j,str.length()-j);if(str[0]=='-'){flag=1;str=str.substr(1,str.length()-1);}else if(str[0]=='+')str=str.substr(1,str.length()-1);for(int i=0;i<str.length();++i){if(str[i]>='0'&&str[i]<='9'&&resu<INT_MAX)resu=10*resu+(str[i]-'0');elsebreak;}if(flag)resu=flag?-resu:resu; if(resu>INT_MAX)resu=INT_MAX;else if(resu<INT_MIN)resu=INT_MIN;return resu; }};
讨论区更简单的实现代码如下:
int myAtoi(string str) { long result = 0; int indicator = 1; for(int i = 0; i<str.size();) { i = str.find_first_not_of(' '); if(str[i] == '-' || str[i] == '+') indicator = (str[i++] == '-')? -1 : 1; while('0'<= str[i] && str[i] <= '9') { result = result*10 + (str[i++]-'0'); if(result*indicator >= INT_MAX) return INT_MAX; if(result*indicator <= INT_MIN) return INT_MIN; } return result*indicator; }}
2016.09.04更新 JAVA代码
public class Solution { public int myAtoi(String str) { long res = 0; boolean flag = true; str = str.trim(); for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if(i == 0 && (ch == '+' || ch == '-')) { flag = ch == '+' ? true : false; } else if(ch >= '0' && ch <= '9') { res = 10 * res + (ch - '0'); } else { break; } if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) { break; } } res = flag ? res : -1 * res; if(res > (long)Integer.MAX_VALUE) { res = Integer.MAX_VALUE; } else if(res < (long)Integer.MIN_VALUE) { res = Integer.MIN_VALUE; } return (int)res; }}
0 0
- leetcode之路008 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之8----String to Integer (atoi)
- LeetCode 之 String to Integer (atoi)
- leetcode 刷题之路 44 String to Integer (atoi)
- LeetCode之路——String to Integer (atoi)
- leetcode-008:String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- [LeetCode OJ][008]String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- [LeetCode]-008-String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- Delphi学习第三天
- Mysql中创建用户和授权的方法
- c++类类型的一个问题!
- Web_url
- 【计蒜客系列】挑战难题21:最大子阵列
- leetcode之路008 String to Integer (atoi)
- sift是图像匹配的非常经典的算法
- 漫水填充算法的一个简单实现(Qt版)
- HDU 1241 Oil Deposits 数草坪
- #1097 : 最小生成树一·Prim算法
- UVA 644
- 《推荐系统实践》协同过滤算法源代码
- Ubuntu 14.04安装Broadcom BCM4352网卡驱动
- Northcott Game - HDU 1730 Nim