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

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

时间:2016-03-28 11:48:34      阅读:114      评论: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.

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

""
=>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)

标签:

原文地址:http://www.cnblogs.com/lianliang/p/5328401.html

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