C++atoiのカスタム実装:異常な入力考慮
1535 ワード
タイトルの説明
文字列を整数に変換するには、文字列を使用して整数を変換できないライブラリ関数が必要です.値が0または文字列が正当な値でない場合は0を返します.
説明を入力:
出力の説明:
入力例:
出力例:
0
ポイント:異常入力は周到に考慮しているか
1.空のポインタ
2.空の文字列
3.プラスマイナス
4.特殊記号
5オーバーフロー
文字列を整数に変換するには、文字列を使用して整数を変換できないライブラリ関数が必要です.値が0または文字列が正当な値でない場合は0を返します.
説明を入力:
, ,
出力の説明:
, 0
入力例:
+2147483647
1a33
出力例:
2147483647
0
ポイント:異常入力は周到に考慮しているか
1.空のポインタ
2.空の文字列
3.プラスマイナス
4.特殊記号
5オーバーフロー
class Solution {
public:
int StrToInt(string str) {
if(str.empty()) return 0; // !=
int end=str.size()-1;
int startidx=0;
while(startidx<=end&&str[startidx]==' ') startidx++; // , 。
if(startidx>end) return 0; //
bool positive=true;
int realidx=startidx;
if(str[realidx]=='+')
++realidx;
else if(str[realidx]=='-'){//
++realidx;
positive=false;
}else if(str[realidx]'9')// , ++, , 。
return 0;
long long result=0;
while(realidx<=end)
{
if(str[realidx]<='9'&&str[realidx]>='0'){
result=10*result+str[realidx]-'0';
if((positive&&result>INT_MAX)||(!positive&&result*(-1)