您的位置:首页 > 其它

【Leetcode】String to Integer (atoi)

2016-06-06 20:34 232 查看
题目链接:https://leetcode.com/problems/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.

思路:

各种边界会烦死人的。。。

算法:

[java] view
plain copy

 





public int myAtoi(String str) {  

    if (str == null || str.equals(""))  

        return 0;  

    str = str.trim();  

    String flag = "+";  

    int i = 0;  

    if ("+".equals(str.charAt(0) + "")) {  

        i++;  

        flag = "+";  

    } else if ("-".equals(str.charAt(0) + "")) {  

        i++;  

        flag = "-";  

    }  

    double sum = 0;  

    while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {  

        sum = sum * 10 + Integer.parseInt("" + str.charAt(i));  

        i++;  

    }  

    if (flag.equals("-")) {  

        sum = -sum;  

    }  

    if (sum > Integer.MAX_VALUE) {  

        sum = Integer.MAX_VALUE;  

    }  

    if (sum < Integer.MIN_VALUE) {  

        sum = Integer.MIN_VALUE;  

    }  

    return (int) sum;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: