把字符串转换成整数

将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。

Iuput:
+2147483647
1a33

Output:
2147483647
0

 

 

C++:

 1 class Solution {
 2 public:
 3     int StrToInt(string str) {
 4         if (str.size() == 0)
 5             return 0 ;
 6         bool isNegative  = false ;
 7         int res = 0 ;
 8         if (str[0] == '-'){
 9             isNegative = true ;
10         }
11         for(int i = 0 ; i < str.size() ; i++){
12             if (i == 0 && (str[i] == '+' || str[i] == '-')){
13                 continue ;
14             }
15             if (str[i] < '0' || str[i] > '9'){
16                 return 0 ;
17             }
18             res = res*10 + (str[i] - '0') ;
19         }
20         if (isNegative){
21             res = -res ;
22         }
23         return res ;
24     }
25 };

 

posted @ 2019-03-26 10:53  __Meng  阅读(204)  评论(0)    收藏  举报