首页 > 其他 > 详细

把字符串转换成整数

时间:2018-02-02 10:12:45      阅读:170      评论:0      收藏:0      [点我收藏+]

题目描述

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

输入描述:

输入一个字符串,包括数字字母符号,可以为空

输出描述:

如果是合法的数值表达则返回该数字,否则返回0

思路:多考虑特殊情况
 1 class Solution {
 2 public:
 3     int atoi(string &str)
 4     {
 5         int sum=0;
 6         for(int idx=0; idx<str.size(); ++idx)
 7         {
 8             if(str[idx]<0 || str[idx]>9)return 0;
 9             else sum=sum*10+str[idx]-0;
10         }
11         return sum;
12     }
13     int StrToInt(string str) {
14         if(str.size()==0)return 0;
15         bool isActive=true;
16         if(str[0]<0 || str[0]>9)
17         {
18             if(str[0]==+)
19             {
20                 isActive=true;
21             }else if(str[0]==-)
22             {
23                 isActive=false;
24             }else{
25                 return 0;
26             }
27             str=str.substr(1, str.size()-1);
28         }
29         int res=atoi(str);
30         if(!isActive)res=-res;
31         return res;
32     }
33 };

 

把字符串转换成整数

原文:https://www.cnblogs.com/jeysin/p/8403632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!