Untitled

Run Settings
LanguageC++
Language Version
Run Command
#include <iostream> #include <vector> using namespace std; class Solution { public: int myAtoi(string str) { vector<char> no_space, no_sign, ans_v; int i = 0, flag; //***從非空白的地方開始把 str 存進 no_space while(str[i] == ' ' && i <= str.length()){ i++; } for(int c = i; c < str.length(); c++){ no_space.push_back(str[c]); } //*** //***判斷並記錄開頭是否有正負號,然後將正負號以外的剩餘字串存進 no_sign if(no_space[0] == '-'){ i = 1; flag = 1; } else if(no_space[0] == '+'){ i = 1; flag = 0; } else{ i = 0; flag = 0; } for(int c = i; c < no_space.size(); c++){ no_sign.push_back(no_space[c]); } //*** i = 0; int digit = 1, ans = 0, size; //***把 no_sign 的數字部分存入 ans_v (如果開頭不是數字則為不合法,ans_v 會是NULL) while(no_sign[i] >= 48 && no_sign[i] <= 57){ i++; } for(int c = 0; c < i; c++){ ans_v.push_back(no_sign[c]); } //*** //***把 ans_v 的內容轉成數字 size = ans_v.size(); for(int c = 0; c < size; c++){ ans += (ans_v.back() - 48) * digit; ans_v.pop_back(); if((digit * 10) / digit != 10){ if(flag == 0){ ans = INT32_MAX; } else if(flag == 1){ ans = INT32_MIN; } break; } //檢查溢位 digit *= 10; } //*** if(flag == 1 && ans > INT32_MIN){ ans = -ans; } return ans; } }; int main() { string str = "-912834723"; Solution answer; cout << answer.myAtoi(str) << endl;; return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines