您好,登錄后才能下訂單哦!
8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
題目大意:該題目是說將string類型的字符串轉換成整型數據,類似于C++庫里的atoi函數,解決該題目的關鍵在于兩個方面:
(1)字符串格式的合法判斷
(2)轉換結果的溢出判斷
首先,對于字符串格式,空格不計入計算,應從第一個非空字符開始判斷,首字母只能是符號(+、-)與數字的一種;從計算開始遍歷字符串,到最后一位數字為止;
其次,對于轉換結果,我們知道整型數據的范圍是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范圍則返回最大與最小值。所以我們可以開始用long long類型的變量存儲結果;
代碼如下:
class Solution { public: int myAtoi(string str) { if (str.empty()) return 0; int flag = 1;//flag 1正 -1負 long long result = 0; int i = 0; while (str[i] == ' ') { i++; } if (str[i] == '-') { i++; flag = -1; } else if (str[i] == '+') { i++; } for (int j = i; j < str.length(); j++) { if (str[j] >= '0' && str[j] <= '9') { result = result * 10 + (str.at(j) - '0'); if (result > 2147483647) { if (flag == 1) result = INT_MAX; else { result = INT_MIN; flag = 1; } break; } } else break; } return flag * result; } };
2016-08-09 00:18:49
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。