LeetCode--String to Integer (atoi)

39 篇文章 0 订阅

String to Integer (atoi)

1 题目

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.

2 分析

这题将string类型的字符转变为int类型,其实转换的过程不复杂,只是限制条件太多,需要自己找出那些转换是合法的,有一下几个部分需要注意的。

2.1 特殊的情况

        1. 形如--2之类的string是不合法的,不能做出转换,返回0.

        2. 形如13+8之类的转换是合法的,返回13.

        3. 形如-2-之类的转换的合法的,返回-2.

注意上面的几种情况,解出这道题目就不难了。

2.2数据的溢出

在这整个过程中,string转化为int类型的数据可能会大于long long 类型,所以我们在sum循环相加的时候就应该开始做出判断,否则到最后数据溢出。

3 源码

class Solution {
public:
	int getIndex(string str) {
		int index = -1;
		for(int i = 0; i < str.size(); i++) {
			if(str[i] != ' ') {
				index = i;
				break;
			}
		}
		return index;
	}
	int getLastIndex(int index, string str) {
		int lastIndex = str.size();
        int tag = 0;
		for(int i = index; i < str.size(); i++) {
			if((str[i] < '0'||str[i] > '9')&&!(str[i] == '-'||str[i] == '+')) {
				lastIndex = i;
				break;
			}
		}
        //cout << "lastIndex" << lastIndex << endl;
		return lastIndex;
	}
    int myAtoi(string str) {
        int index = getIndex(str);
        //cout << "index" << index << endl;
        int flag = 0;
        string target;
        if(index == -1||str[index] != '-'&&str[index] != '+'&&(str[index] < '0'||str[index] > '9')) {
        	return 0;
        } else {
        	int lastIndex = getLastIndex(index, str);
        	
        	if(str[index] == '-') {
        		flag = -1;
        		target = str.substr(index+1, lastIndex-index-1);
                
        	} else if(str[index] == '+') {
        		flag = 1;
        		target = str.substr(index+1, lastIndex-index-1);
        	} else {
        		target = str.substr(index, lastIndex-index);
        	}
            int tag = 0;
            for(int i = 0; i < target.size(); i++) {
                if(target[i] < '0'||target[i] > '9') {
                    lastIndex = i;
                    break;
                }
            }
            target = target.substr(0, lastIndex);
            //cout << target << endl;
        }

        long long sum = 0;
        for(int i = 0; i < target.size(); i++) {
            if(target[i] < '0'||target[i] > '9') {
                return 0;
            }
            sum = sum*10 + (target[i] - '0');
            if(sum > INT_MAX) {
                break;
            }
        }
        //cout << "flag" << flag << endl;
        if(flag == -1) {
        	sum = 0-sum;
        }
      	
        //cout << sum << endl;
        if(sum < INT_MIN) {
            return INT_MIN;
        } else if(sum > INT_MAX) {
            return INT_MAX;
        }else {
            return sum;
        }
    }
};

## [更多技术博客](https://vilin.club/):https://vilin.club/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值