String to Integer (atoi) LeetCode 解题报告

题目

就是把输入的字符串转为整数,具体要求如下:
1、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.
译:(这个函数最开始丢弃空白字符知道第一个不空白字符的字符出现,然后从这个字符开始,接受一个可选的正号或负号,随后是尽可能多的数字,然后将它们解释为数值)。

2、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.
译:(这个字符串可以包含那些形成整数的额外字符,这些字符将被忽略,对这个函数的将不起作用)。[这句翻译我也有点迷糊,有更好的翻译希望留言讨论]

3、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.
译:(如果这个开始的为非空白字符不是合法的整数,或者是这个字符序列不存在因为它要么是空的要么是纯空白字符,不会发生转换)。

4、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.
译:(如果没有发生合法的转换,返回0. r如果这个正确值超出可表达的范围,返回整数的最大值(2147483647)或最小值(-2147483648))。

思路

题目细节较多,具体的要求在上面四点中,难度在于各种情况考虑周全。

代码

public int myAtoi(String str) {
        int i = 0,res = 0,sign = 0,len = str.length()-1;
        while(i <= len && str.charAt(i) == ' ')
            i++;
        if(i <= len && (str.charAt(i) == '-' || str.charAt(i) == '+')){
            if(str.charAt(i) == '-'){
                sign = -1;

            }
            i++;
        }
        while(i <= len && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
            if(res > Integer.MAX_VALUE / 10 || ((res == Integer.MAX_VALUE / 10) 
                    && str.charAt(i)-'0' > 7)){
                if(sign == 1){
                    return Integer.MAX_VALUE;
                }else{
                    return Integer.MIN_VALUE;
                }
            }
            res = res*10 + str.charAt(i++)-'0';
        }
        return res*sign;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值