内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

leetCode8.StringtoInteger(atoi)字符串

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)

手機(jī)網(wǎng)站建設(shè)
新蔡县| 南丹县| 镇江市| 内丘县| 麻江县| 车致| 上林县| 沙洋县| 台安县| 云龙县| 玛多县| 昭觉县| 昌宁县| 屯留县| 库尔勒市| 图木舒克市| 明光市| 永州市| 沙河市| 阿拉尔市| 海门市| 峨眉山市| 云林县| 东安县| 新田县| 贵定县| 巴南区| 屯留县| 新宁县| 白河县| 社会| 子洲县| 依兰县| 罗山县| 顺昌县| 北安市| 富民县| 夏河县| 英吉沙县| 巩留县| 桂平市|