您好,登錄后才能下訂單哦!
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類型的字符串轉(zhuǎn)換成整型數(shù)據(jù),類似于C++庫里的atoi函數(shù),解決該題目的關(guān)鍵在于兩個(gè)方面:
(1)字符串格式的合法判斷
(2)轉(zhuǎn)換結(jié)果的溢出判斷
首先,對(duì)于字符串格式,空格不計(jì)入計(jì)算,應(yīng)從第一個(gè)非空字符開始判斷,首字母只能是符號(hào)(+、-)與數(shù)字的一種;從計(jì)算開始遍歷字符串,到最后一位數(shù)字為止;
其次,對(duì)于轉(zhuǎn)換結(jié)果,我們知道整型數(shù)據(jù)的范圍是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范圍則返回最大與最小值。所以我們可以開始用long long類型的變量存儲(chǔ)結(jié)果;
代碼如下:
class Solution { public: int myAtoi(string str) { if (str.empty()) return 0; int flag = 1;//flag 1正 -1負(fù) 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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。