LeetCode--String to Integer (atoi)
2015-01-07 23:49
330 查看
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.
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.
class Solution { public: int atoi(const char *str) { string temp=""; int loc=0; while(str[loc] != '\0') { if(str[loc]!=' ') break; loc++; } long long res=0; if(str[loc] == '-') { while(str[loc] != '\0') { if(str[loc] != '0') break; loc++; } if(str[loc] == '\0') return 0; for(int i=loc+1; str[i] != '\0'; i++) { if(str[i]<48 || str[i] > 57) break; res = res*10+str[i]-48; if(res-1 > INT_MAX) return INT_MIN; } if(res-1 > INT_MAX) return INT_MIN; return -res; } else { while(str[loc] != '\0') { if(str[loc] != '0') break; loc++; } if(str[loc] == '\0') return 0; if(str[loc] == '+') loc = loc+1; for(int i=loc; str[i]!='\0'; i++) { if(str[i]<48 || str[i] > 57) break; res = res*10+str[i]-48; if(res > INT_MAX) return INT_MAX; } if(res > INT_MAX) return INT_MAX; return res; } } };
相关文章推荐
- leetcode 54: 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 54: 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)Dec 27 '117626 / 35090
- [LeetCode] String to Integer (atoi) 解题报告
- LeetCode 8 - 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)