码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]String to Integer (atoi)

时间:2015-12-05 09:40:53      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

主要是一下步骤

1.delete space in front of str

2.check if str startsWith other characters

3.check if str is positive

4.check the end of str

5.check if overflow

public class Solution {
    public int myAtoi(String str) {
        while (str.length() > 0 && str.charAt(0) == ‘ ‘) {
            str = str.substring(1);
        }
        if (str.length() == 0 || (str.charAt(0) != ‘+‘ && str.charAt(0) != ‘-‘ && !isNum(str.charAt(0)))) {
            return 0;
        }
        int positive = 1;
        if (str.charAt(0) == ‘+‘) {
            str = str.substring(1);
        } else if (str.charAt(0) == ‘-‘) {
            positive = -1;
            str = str.substring(1);
        }
        boolean flg = true;
        int i = 0;
        for (; i < str.length(); i++) {
            if (!isNum(str.charAt(i))) {
                flg = false;
                break;
            }
        }
        if (!flg) {
            str = str.substring(0, i);
        }
        if (str.length() > 11) {
            return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        if (str.length() == 0) {
            return 0;
        }
        Long tmp = Long.valueOf(str);
        if (tmp > Integer.MAX_VALUE) {
            return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        return Integer.valueOf(str) * positive;
    }
    public boolean isNum(char c) {
        return c <= ‘9‘ && c >= ‘0‘;
    }
}

 

[LeetCode]String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5020974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!