码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode-8(Java) String to Integer (atoi)

时间:2015-08-03 18:15:05      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

传送门:https://leetcode.com/problems/string-to-integer-atoi/

把字符串转换成整型,注意空格和符号即可。

public class Solution {
    public int myAtoi(String str)
    {
        if(str == null)
            return 0;
        str = str.trim();//去掉字符串前面的空格
        int len = str.length();
        if(len == 0)
            return 0;
        char signal = ‘+‘;
        double res = 0;
        for(int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if(ch == ‘-‘ || ch == ‘+‘)
            {
                if(i != 0)
                    return 0;
                else
                {
                    if(ch == ‘-‘)
                        signal = ‘-‘;
                }
            }
            else if(ch >= ‘0‘ && ch <= ‘9‘)
            {
                res = res * 10 + ch - ‘0‘;
            }
            else
                break;
        }
        if(signal == ‘-‘)
            res = -res;
        if(res > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        else if(res < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        else
            return (int)res;
    }    
}

 

Leetcode-8(Java) String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/zetrov/p/4699663.html

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