String to Integer (atoi) - LintCode

204 篇文章 0 订阅

描述:
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
样例:
“10” =>10
“-1” => -1
“123123123123123” => 2147483647
“1.0” => 1

思路
对于给定的字符串,需要先处理字符串str,提取其中的合法整数。
先要判断str中是否存在数字,不存在直接返回0,否则求得str中第一个数字出现的位置start,str[start-1]只能是空格,正号或者负号,str[0]到str[start-2]只能是空格,否则返回0。之后提取合法的数字,从str[start]开始向后遍历,遇到非数字即停止,最后计算截取到的字符串所代表的整数的值。

#ifndef C54_H
#define C54_H
#include<iostream>
#include<string>
#include <math.h>
using namespace std;
class Solution {
public:
    /**
    * @param str: A string
    * @return: An integer
    */
    int atoi(string &str) {
        // write your code here
        if (str.empty())
            return 0;
        long long res = 0;
        bool isNeg = false;
        string nums("0123456789");
        int posNum = 0;
        //找到第一个数字出现的位置
        if (str.find_first_of(nums) != string::npos)
            posNum = str.find_first_of(nums);
        else
            return 0;
        //若第一个数字前不是是空格,-或者+,不合法
        if (posNum > 0 && str[posNum - 1] != ' ' && str[posNum - 1] != '-' && str[posNum-1] != '+')
            return 0;
        //从字符串开始到第一个字母的前一个位置之前,只能是空格,否则不合法
        for (int i = 0; i< posNum - 1; ++i)
        {
            if (str[i] != ' ')
                return 0;
        }
        //判断是否是负数
        if (posNum>0 && str[posNum - 1] == '-')
            isNeg = true;
        str = str.substr(posNum);
        //寻找合法数字的结束位置,遇到非数字就结束(处理了小数问题)
        int end = 0;
        for (int i = 0; i<str.size(); ++i)
        {
            if (isdigit(str[i]))
            {
                end = i;
            }
            else
                break;
        }
        //对于提取到的合法整数,计算其值
        str = str.substr(0, end + 1);
        for (int j = 0; j <str.size(); ++j)
            res += (str[j] - '0')*pow(10, str.size() - 1 - j);
        if (isNeg)
            res = -res;
        if (res > INT_MAX)
            res = INT_MAX;
        else if (res < INT_MIN)
            res = INT_MIN;
        return res;
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值