Leetcode008. String to Integer (atoi)
Posted zeroArn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 string 14 { 15 if(str[i]!=‘ ‘)break; 16 } 17 if(str[i]==‘+‘)i++; // deal with signature 18 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; //overflow 25 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)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-面试算法经典-Java实现008-String to Integer (atoi) (字符串转成整数)
No.008:String to Integer (atoi)
Reverse Words in a String leetcode
leetcode:Nth to Last Node in List