[LeetCode] String to Integer (atoi)

题目

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

思路

这道题属于Easy难度的,唯一需要留意的是要处理各类输入和处理溢出。

一、首先对几类无效输入进行处理:

1.字符串长度为0

2.字符串长度为1,且这个字符不是数字

3.字符串长度大于1,且第一个字符不是数字,'+'或者'-'

以上情况均返回0,剩下符合条件的字符串要么'+'或'-'开头,要么数字开头。如果'-'开头,isNegative为true,否则为false。

二、为了处理溢出,先将返回值声明为long类型,如果溢出了,返回max或min,否则显示转换为int类型,需要注意的是符号要对。


代码

public class Solution {
    public int myAtoi(String str) {
        long ret = 0;
        int max = Integer.MAX_VALUE, min = Integer.MIN_VALUE;
        boolean isNegative = false;
        
        str = str.trim();
        int len = str.length();
        if (len == 0)
            return 0;
        
        char c = str.charAt(0);
        
        if (len == 1 && (c < '0' || c > '9'))
            return 0;
        
        if ((c != '+')&&(c != '-')&&(c < '0' || c > '9'))
            return 0;
        
        isNegative = (c == '-') ? true : false;
        
        for (int i = (c == '+' || c == '-') ? 1 : 0; i < len; i++) {
            c = str.charAt(i);
            
            if (c < '0' || c > '9')
                break;
            else {
                ret = ret * 10 + (c - '0');
                
                if (isNegative && (0-ret) < min)
                    return min;
                if (!isNegative && ret > max)
                    return max;
            }
        }
        
        if (isNegative)
            ret = 0 - ret;
        return (int)ret;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值