[LeetCode]-algorithms-String to Integer (atoi)

Posted 练子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]-algorithms-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.

需求:字符串转成数字,需要识别正负号

""
=>0
-1
=>-1
+-1
=>0
1234567890123456789012345678901234567890
=>0
"2147483648"
=>2147483647

public int myAtoi(String str) {
        str = str.trim();
        if(null==str || "".equals(str))
            return 0;
        char flag = ‘+‘;
        int i = 0;
        if(str.charAt(0)==‘+‘){
            flag = ‘+‘;
            i++;
        }else if(str.charAt(0)==‘-‘){
            flag = ‘-‘;
            i++;
        }
        double result = 0.0;
        if(str.length()>12)
            return 0;
        while(str.length()>i && str.charAt(i)>=‘0‘ && str.charAt(i)<=‘9‘){
            result = result * 10 + (str.charAt(i)-‘0‘);
            i++;
        }
        if(flag==‘-‘)
            result = -result;
        if(result>Integer.MAX_VALUE)
            result = Integer.MAX_VALUE;
        if(result<Integer.MIN_VALUE)
            result = Integer.MIN_VALUE;
        return (int)result;
    }

 

以上是关于[LeetCode]-algorithms-String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 352 & leetcode 239 & leetcode 295 & leetcode 53 & leetcode 209

如何做LeetCode

leetcode可以写在简历上吗

[Leetcode]leetcode1-10题随记

leetcode分类刷题(续2)

leetcode分类刷题