剑指Offer 把字符串转换成整数

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 
输入描述:
输入一个字符串,包括数字字母符号,可以为空


输出描述:
如果是合法的数值表达则返回该数字,否则返回0

输入例子:
+2147483647
        1a33

输出例子:
2147483647
        0

思路:

写了个判断是不是数字字符串的函数。

不是数字字符串直接返回0,是数字字符串,判断首字母是不是符号,是从第二个位置开始计数。

AC代码:

 1 class Solution {
 2 public:
 3     bool isNumble(string str, int n)
 4     {
 5         int i = 0;
 6         if (str[0] == '+' || str[0] == '-')
 7             i=1;
 8         for (; i<n; i++)
 9         {
10 
11             if (str[i]<'0' || str[i]>'9')
12                 return false;
13         }
14         return true;
15     }
16 
17     int StrToInt(string str) {
18         int n = strlen(str.c_str());
19         int ans = 0;
20         if (isNumble(str,n))
21         {
22             int i=0;
23             if (str[0] == '+' || str[0] == '-')
24                 i = 1;
25             for (; i<n; i++)
26             {
27                 ans *= 10;
28                 ans += (int)(str[i] - '0');
29             }
30             if (str[0] == '-')
31                 ans = 0 - ans;
32             return ans;
33         }
34         else
35             return 0;
36     }
37 };
原文地址:https://www.cnblogs.com/SeekHit/p/5807595.html