Leetcode 8. String to Integer (atoi) [medium][java]

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.

Link: link.

Note:

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

Considerations

  1. firstly use string.trim() to remove spaces at the front
  2. check the first character is ‘+’ ‘-’ or digit
  3. check if the number is outside the 32-bit integer range

Ignored points
(1) str = “”
(2) str contains only spaces, e.g. str = " "
(3) convert other types to int type : (int) Variable
(4) if the number is exceed the range, the sign of the number maybe changed

Solution 1: use double type to store the number

class Solution {
    public int myAtoi(String str) {
        
        // check null string and str = ""
        if(str == null || str.length() < 1)
            return 0;
        
        str = str.trim();
        
        // check str contains only spaces. e.g. str = " "
        if(str.length() < 1)
            return 0;
        
        
        // check if the first character is '+' or '-'
        char sign = '+';
        int length = 0;
        if(str.charAt(length) == '-') {
            sign = '-';
            length++;
        } else if(str.charAt(length) == '+')
            length++;
        
        /**Integer has range [-2147483648 , 2147483647] in Java. If the number is -214748364, the algorithm processes it as a positive integer and then change sign. The number would exceed the integer range if an integer is used.*/
        //so cannot use long type
        double num = 0;
        while(str.length()>length && str.charAt(length) >= '0' && str.charAt(length) <= '9') {
            num = num*10+str.charAt(length)-'0';
            length++;
        }
        
        if(sign == '-')
            num = -num;
        
        if(num > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        
        if(num < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        
        return (int)num;
            
    }
}

Solution 2: use int type to store the number; when getting the number, check if it exceeds the maximal

class Solution {
    public int myAtoi(String str) {
        
        // check null string and str = ""
        if(str == null || str.length() < 1)
            return 0;
        
        str = str.trim();
        
        // check str contains only spaces. e.g. str = " "
        if(str.length() < 1)
            return 0;
        
        
        // check if the first character is '+' or '-'
        char sign = '+';
        int length = 0;
        if(str.charAt(length) == '-') {
            sign = '-';
            length++;
        } else if(str.charAt(length) == '+')
            length++;
        
        
        int num = 0;
        while(str.length()>length && str.charAt(length) >= '0' && str.charAt(length) <= '9') {
            if(Integer.MAX_VALUE/10 < num || (Integer.MAX_VALUE/10 == num && Integer.MAX_VALUE % 10 < str.charAt(length)-'0'))
                return sign=='-'?Integer.MIN_VALUE:Integer.MAX_VALUE;
            num = num*10+str.charAt(length)-'0';
            length++;
        }
        
        if(sign == '-')
            num = -num;
        
        
        return num;
            
    }
}

if use long type to store number, an error case is shown below
error testing case

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值