String to Integer (atoi)--LeetCode

來源:互聯網
上載者:User

標籤:c++   leetcode   演算法   

這種題的考察重點並不在於問題本身,而是要注意corner case的處理,整數一般有兩點,一個是正負符號問題,另一個是整數越界問題。思路比較簡單,就是先去掉多餘的空格字元,然後讀符號(注意加號或減號都有可能,也有可能沒有符號),接下來按順序讀數字,結束條件有三種情況:(1)異常字元出現(按照C語言的標準是把異常字元起的後面全部截去,保留前面的部分作為結果);(2)數字越界(返回最接近的整數);(3)字串結束。

思路:從頭開始尋找字元,找打標誌位,然後開始計算

#include <iostream>#include <vector>#include <string>#include <limits> using namespace std;/*這裡需要注意三點 一個越界 一個正負數 一個字串結束 */int StringToInt(string& str){if(str.length()==0)return 0;int i;int flag=1;int result=0;int digit;for(i=0;i<str.length();i++)if(str[i] != ' ')break;if(str[i]=='+')i++;if(str[i]=='-'){flag = 0;i++;}for(;i<str.length();i++){if(str[i]<'0' || str[i]>'9')break;digit = str[i]-'0';if(flag && (numeric_limits<int>::max()-result*10) <= digit)return numeric_limits<int>::max();else if(!flag && (numeric_limits<int>::min()+result*10) >= digit*-1)return numeric_limits<int>::min();result = result*10 + digit;}return flag == 1? result:-result;}int main(){string str("2147483649");cout<<StringToInt(str)<<endl;return 0;}


String to Integer (atoi)--LeetCode

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.