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

Leetcode #8 String to Integer (atoi) (E)

时间:2015-10-06 01:51:36      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

[Problem]

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.

 

[Analysis]

这题的要点只在于将corner cases考虑周全。实在无法通过OJ的话参考spoiler基本就没问题了。

 

[Solution]

public class Solution {
    public int atoi(String str) {
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        
        int sign = 1;
        int i = 0;
        if (str.charAt(0) == ‘+‘) {
            i++;
        } 
        
        if (str.charAt(0) == ‘-‘) {
            sign = -1;
            i++;
        }
        
        long result = 0;
        for (; i < str.length(); i++) {
            int digit = str.charAt(i) - ‘0‘;
            if (digit > 9 || digit < 0) {
                break;
            } else {
                if (result > Long.MAX_VALUE/10) {
                    break;
                }

                result *= 10;
                if (result > Long.MAX_VALUE - digit) {                    
                    break;
                }

                result += digit;
            }            
        }
        
        result = result * sign;
        if (result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;            
        } else if (result < Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;            
        }    
    
        return (int)result;        
    }
}

 

Leetcode #8 String to Integer (atoi) (E)

标签:

原文地址:http://www.cnblogs.com/zhangqieyi/p/4856614.html

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