字符串转整数

来源:互联网 发布:网络接入设备集线器 编辑:程序博客网 时间:2024/06/18 14:07

字符串转整数

题目
题目也没给样例,做起来觉得怪怪的,注意以下几点之后就ac啦

  1. 需要去掉首尾空字符
  2. 需要判断符号
  3. 碰到非数字字符就舍弃
#include <iostream>#include <bits/stdc++.h>using namespace std;/*atoi (表示 ascii to integer)把字符串转换成整型数的一个函数1、需要去掉首尾空字符2、需要判断符号3、碰到非数字字符就舍弃 */class Solution {public:    int myAtoi(string str) {        //去掉首尾空字符        str.erase(0,str.find_first_not_of(" "));        str.erase(str.find_last_not_of(" ") + 1);         if(str.length() == 0)            return 0;        double result = 0;        int i = 0;        //判断正负        int flag = 1;        if(str[0] == '-'){            flag = -1;            i++;        }else if(str[0] == '+'){            flag = 1;            i++;        }        //计算值        for( ; i < str.length(); i++){            int t = str[i] - '0';            //cout << t << endl;            if(t < 0 || t > 9){                break;            }            result = result * 10 + t;            if(result * flag > INT_MAX) return INT_MAX;            if(result * flag < INT_MIN) return INT_MIN;        }        result = result * flag;        return (int)result;    }};int main(){    Solution s;    cout << s.myAtoi("   010i");    return 0;} 

在库函数中本来就有一个atoi函数能够将字符串转为整数
源码
http://blog.csdn.net/u014082714/article/details/44775269