字串轉換為數字
阿新 • • 發佈:2019-02-18
1、 題目
把字串轉換成整數
2、思路
1.功能測試
正數/複數/0
2.邊界值測試
最大的正整數/最小的負整數(資料上下溢位)
3.特殊輸入測試
空字串“”的處理,返回0,設定非法輸入
字串只有符號位的處理,返回0,設定非法輸入
輸入的字串中有非數字字元,返回0,設定非法輸入
class Solution {
public:
int StrToInt(string str)
{
const char*cstr = str.c_str();
if(str.empty())
{
return 0;
}
long long sum = 0;
// 處理符號位
int IF = 1;
if(*cstr=='+')
{
IF = 1;
cstr++;
}
else if(*cstr=='-')
{
IF = -1;
cstr++;
}
while(*cstr!='\0')
{
if (*cstr>='0'&&*cstr<='9')
{
sum = sum*10+(*cstr-'0');
cstr++;
//如果溢位,則標記為非法輸入
if(((IF>0)&&(sum>0x7FFFFFFF)||(IF<0)&&(sum>0x80000000)))
{
return 0;
}
}
else
{
return 0;
}
}
sum = sum*IF;
return (int)sum;
}
};