LeetCode 8. String to Integer (atoi)

题目:

实现将字符串转换为整数。

函数丢弃空白符,直到找到第一个非空白符。从首个非空白符开始,取一个可选的初始正负号,后跟尽可能多的数字,并将它们解释为一个数值。

字符串可以包含构成整数的字符之后的附加字符,这些字符将被忽略,并且对函数的行为没有影响。

如果str中的第一个非空格字符序列不是有效的整数,或者由于str为空或只包含空格字符而不存在这样的序列,则不执行转换。

也就是说:

字符串前面有空格,则删除空格

删除空格后,如果首字符是数字或正负号,则进行转换

如果删除空格后的首字符不是数字或正负号,则不进行转换,如果不能执行有效的转换,则返回一个零值。

并且,按照NOTE可见,如果超出范围,则输出边界值

 

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.
Input: "42"                   Output: 42
Input: "   -42"               Output: -42
Input: "4193 with words"      Output: 4193
Input: "words and 987"        Output: 0
Input: "-91283472332"         Output: -2147483648

思路:

按以下几个步骤进行:

1. 去除空白符

2. 检查去除空白符之后的首字符

3. 如果首字符为正负号或数字,开始转换;否则返回0

转换算法:

从非空白符且为正负号/数字的首个字符开始转换,设置正负号标记flag=1,如果首字符为负号,则flag=-1

纯数字的转换为:设置整数re记录需返回的结果,每次re*10+当前值

 

【注意】最重要的部分是越界判断!!!

负数范围是到-2147483648,正数范围是到2147483647,因此在每次对base*10+当前数时,先判断base是否≥214748364

如果超过214748364,则正负数分别返回自己的边界值

如果等于214748364,根据当前数的大小判断,如果当前数大于8,则无论是整数还是负数都越界了,返回分别的边界值;如果≤7,则进行正常加减,直接返回 flag*(base*10 + t-'0')

 

代码:
 

class Solution {
    public int myAtoi(String str) {
        // 空字符串
        if(str.length()==0) {
            return 0;
        }
    	
        int loc = 0;
        int flag = 1;
        int base = 0;
        
        // 去除开头空字符
        while(loc<str.length() && str.charAt(loc)==' ') {
            loc++;
        }
        
        // 检查字符串遍历越界
        if(loc>str.length()-1) {
            return 0;
        }
        
        // 判断正负号和首字母是否为非法字符
        if(str.charAt(loc)=='-') {
            flag = -1;
            loc++;
        }else if (str.charAt(loc)=='+') {
            loc++;
        }else if (str.charAt(loc)<'0' || str.charAt(loc)>'9') {
            return 0;
        }
        
        // 数字转换
        for(int i=loc;i<str.length();i++) {
            char t = str.charAt(i);
            if(t<'0'||t>'9') {
                break;
            }
        	
            // 越界判断
            if(base>=214748364) {
                if(base>214748364) {
                    if(flag==1) {
                        return 2147483647;
                    }else {
                        return -2147483648;
                    }
                }else {
                    if((t-'0')>7) {
                        if(flag==1) {
                            return 2147483647;
                        }else {
                            return -2147483648;
                        }
                    }else{
                        return flag*(base*10 + t-'0');
                    }	
                }
            }
            base = base*10 + str.charAt(i)-'0';
        }
        
        // 返回结果
        return base*flag;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值