8. String to Integer (atoi)
創(chuàng)新互聯(lián)建站主營吳興網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都app開發(fā),吳興h5重慶小程序開發(fā)搭建,吳興網(wǎng)站營銷推廣歡迎吳興等地區(qū)企業(yè)咨詢
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)鍵在于兩個方面:
(1)字符串格式的合法判斷
(2)轉(zhuǎn)換結(jié)果的溢出判斷
首先,對于字符串格式,空格不計入計算,應(yīng)從第一個非空字符開始判斷,首字母只能是符號(+、-)與數(shù)字的一種;從計算開始遍歷字符串,到最后一位數(shù)字為止;
其次,對于轉(zhuǎn)換結(jié)果,我們知道整型數(shù)據(jù)的范圍是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范圍則返回最大與最小值。所以我們可以開始用long long類型的變量存儲結(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
分享題目:leetCode8.StringtoInteger(atoi)字符串
標(biāo)題網(wǎng)址:http://www.rwnh.cn/article48/jsdshp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、軟件開發(fā)、建站公司、微信公眾號、App開發(fā)、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)