《劍指offer》把字串轉換成整數
阿新 • • 發佈:2019-01-30
一、題目描述
將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函式。
輸入:
- 輸入可能包含多個測試樣例。
- 對於每個測試案例,輸入為一個合法或者非法的字串,代表一個整數n。
輸出:
- 輸入為一個合法的字串,可以轉換成一定範圍內的整數,則返回這個int型整數。
- 若輸入為一個非法的字串,無法轉換成整數,則輸出
"Invalid result"
。
樣例輸入:
3 // 第一行表示案例的個數
13
-4
+8
樣例輸出:
13
-4
8
二、題目分析
該題目本身實現不難,真正字串轉換程式碼只有幾行,但是這是一道常見的面試題,考察的重點在於對非法輸入的檢查,至少要考慮空字串、正負號、非數字字元、整型資料溢位等情況。下面貼上程式碼,大家也可以看下有沒有沒考慮到的邊界情況。
三、示例程式碼
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isValue; // 標記是否為合法字串
long strToInt(string s)
{
isValue = true;
if (s.size() == 0)
{
isValue = false;
return 0;
}
bool isMinus = false;
int index = 0;
long result = 0;
// 略過非法字元
while (index < s.size() && s[index] != '-' && (s[index] == ' ' || s[index] < '0' || s[index] > '9')) ++index;
//第一個非空白字元為-號
if(s[index] == '-')
{
++index;
isMinus = true;
}
// 如果沒有出現數字,則非法
if (index == s.size())
{
isValue = false ;
return 0;
}
// 正負號後的輸入如果合法,則轉化為整數
while (index < s.size() && s[index] >= '0' && s[index] <= '9')
result = 10 * result + (s[index++] - '0');
// 根據正負號標識轉換正負
result = isMinus ? (-1 * result) : result;
// 判斷是否溢位
if (result > 0x7fffffff || result < (signed int)0x80000000)
{
isValue = false;
return 0;
}
return result;
}
int main()
{
int n = 0;
cin >> n;
cin.sync();
if (n <= 0) return -1;
vector<string> src(n, "");
for (int i = 0; i < n; ++i)
{
getline(cin, src[i]);
}
for (int i = 0; i < n; ++i)
{
long result = strToInt(src[i]);
if (isValue)
cout << result << endl;
else
cout << "The string is invalid!" << endl;
}
system("pause");
return 0;
}