首页 > 代码库 > Leetcode008. String to Integer (atoi)
Leetcode008. String to Integer (atoi)
1 /* improvement on dealing with overflow accroding to this: 2 * https://discuss.leetcode.com/topic/57452/c-solution-beats-100 3 * 4 * be careful about the INT_MAX and INT_MIN 5 * this atoi is not thinking about special char like dot and so on. 6 */ 7 8 class Solution { 9 public:10 int myAtoi(string str) {11 int i,nega_sign=1;12 long long int re=0; //long long re to avoid overflow 13 for(i=0;i<str.size();i++) //skip to all the blank in the front of the string14 {15 if(str[i]!=‘ ‘)break;16 }17 if(str[i]==‘+‘)i++; // deal with signature18 else if(str[i]==‘-‘){ nega_sign=-1;i++;}19 while(i<str.size()&&isdigit(str[i])) 20 /*when the string is over or the current char is not a valid integral number,no more conversion will be performed.21 */22 {23 re=re*10+str[i]-‘0‘;24 if(nega_sign==-1&& -1*re<=INT_MIN)return INT_MIN; //overflow25 else if (nega_sign==1&&re>=INT_MAX)return INT_MAX;26 i++;27 }28 return re*nega_sign;29 }30 };
Leetcode008. String to Integer (atoi)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。