leecode--字符串转整型

 

source: https://leetcode-cn.com/problems/string-to-integer-atoi/

 


Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

    Only the space character ' ' is considered as whitespace character.
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

 

class Solution {

public:

     int myAtoi(string str) {       

    }

};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-integer-atoi
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


我的解答1:

#pragma once

#include <string>
using namespace std;

class str2int {
public:
	int myAtoi(string str) {
		int long res = 0;
		if (str.empty()) {
			return res;
		}
		int len = str.length();
		int signFlag = 1;
		int i = 0;

		while (i < len && (' ' == str[i]))//skip white space
		{
			i++;
		}

		if (len == i) { //return zero if only contains white space!
			return 0;
		}

		if ('+' == str[i]) {
			signFlag = 1;
			i++;
		}
		else if ('-' == str[i]) {
			signFlag = -1;
			i++;
		}
		else if ('0' > str[i] || '9' < str[i]) {//return 0 if the first character is not sign nor number
			return 0;
		}

		if (len == i) {
			return 0;
		}

		for (; i < len; i++) {
			if ('0' <= str[i] && '9' >= str[i]) {
				res = (10 * res + (str[i] - '0'));
				if (signFlag == 1 && res >= INT_MAX) {
					return INT_MAX;
				}
				if (signFlag == -1 && -res <= (INT_MIN)) {
					return INT_MIN;
				}
			}
			else {
				break;
			}
		}


		res = res * signFlag;
		return res;
	}
};

改进1: 最后返回时: return signFlag==1?res:-res; --简洁

改进2:判断是否溢出,我定义了int long res来实现与INT_MAX, INT_MIN的比较,但是有以下更好的方法: 判断res*10+ r是否大于max,可以先判断res结果与max/10的大小关系,如果大于max则res*10肯定越界,例如,res=9,max=87,这样的话res*10肯定越界!如果max/10==res,例如,res=8,max=87,则需要进一步判断r与INT_MAX%10的关系,如过r>7则 res*10+r越界, 于是,当signFlag为正时,越界判断方法:

if ( res > INT_MAX/10 ) || ( res == INT_MAX/10 && r> INT_MAX%10){越界!}

INT_MAX%10 = 7

 

当signFlag为负时:

INT_MIN为-2^31, INT_MAX为2^31-1, 两者的绝对值差1, 上述判断方法仍然可以,例如,当res=8, r= ? ,max=87(假设-88~~87范围),如果,r=8时才会满足越界,这时正好对应-88.

所以:

 

官方解答:

使用状态机实现的一种:  https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/

class Automaton {
    string state = "start";
    unordered_map<string, vector<string>> table = {
        {"start", {"start", "signed", "in_number", "end"}},
        {"signed", {"end", "end", "in_number", "end"}},
        {"in_number", {"end", "end", "in_number", "end"}},
        {"end", {"end", "end", "end", "end"}}
    };

    int get_col(char c) {
        if (isspace(c)) return 0;
        if (c == '+' or c == '-') return 1;
        if (isdigit(c)) return 2;
        return 3;
    }
public:
    int sign = 1;
    long long ans = 0;

    void get(char c) {
        state = table[state][get_col(c)];
        if (state == "in_number") {
            ans = ans * 10 + c - '0';
            ans = sign == 1 ? min(ans, (long long)INT_MAX) : min(ans, -(long long)INT_MIN);
        }
        else if (state == "signed")
            sign = c == '+' ? 1 : -1;
    }
};

class Solution {
public:
    int myAtoi(string str) {
        Automaton automaton;
        for (char c : str)
            automaton.get(c);
        return automaton.sign * automaton.ans;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/
来源:力扣(LeetCode)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值