《劍指offer》把字串轉換成整數,《劍指offer》整數

來源:互聯網
上載者:User

《劍指offer》把字串轉換成整數,《劍指offer》整數

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱:libin493073668@sina.com】


題目連結:http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


題目描述
將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函數。

思路
這一題的坑比較多,主要考慮以下幾點
1.字串的首碼空格需要省略
2.數字前面出現多個加號或減號,則判錯,返回0,如“++123”,“--123”,“+-123”,“-+123”
3.連續的數字被其他符號隔開,則返回0,如“   123a321”,"   123    123",都是返回0
4.如果超出了int範圍(-2147483648--2147483647),返回臨界最大值,也就是說如果是負數返回-2147483648,整數則返回2147483647


class Solution{public:int StrToInt(string str){int len = str.length();int i,j,flag1 = 0,flag2 = 0,num = 1,fu = 0;long long ans = 0;for(i = 0; i<len; i++)if(str[i]!=' ')break;for(; i<len; i++){if(str[i]=='+') flag1++;else if(str[i]=='-') flag2++;else break;}if(flag1+flag2>1) return 0;for(; i<len; i++){if(str[i]>='0' && str[i]<='9'){ans = ans*10+str[i]-'0';if((!flag2)&&ans>=2147483647)return 2147483647;if(flag2&&ans>=2147483648)return -2147483648;}else return 0;}return flag2?-ans:ans;}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.