首页 > 其他 > 详细

String to Integer

时间:2015-04-28 11:07:19      阅读:251      评论:0      收藏:0      [点我收藏+]

String to Integer

问题:

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.

思路:

  只是需要考虑的corner case多一些,思路很简单

我的代码:

技术分享
public class Solution {
    public int myAtoi(String str) {
        if(str==null || str.length()==0 || str.trim().length()==0)  return 0;
        str = str.trim();
        boolean isPlus = true;
        if(str.charAt(0) == ‘-‘)
        {
            isPlus = false;
            str = str.substring(1);
        }
        else
        {
            if(str.charAt(0) == ‘+‘)
                str = str.substring(1);
        }
        long rst = 0;
        for(int i=0; i<str.length(); i++)
        {
            char c = str.charAt(i);
            if(isValidNum(c))
            {
                rst = rst*10 + (c-‘0‘);
                long tmp = (isPlus ? rst : rst*-1);
                if(tmp>Integer.MAX_VALUE)   return Integer.MAX_VALUE;
                if(tmp<Integer.MIN_VALUE)   return Integer.MIN_VALUE;
            }
            else 
                break;
        }
        rst = (isPlus ? rst : rst*-1);
        return (int)rst;
    }
    public boolean isValidNum(char c)
    {
        return c<=‘9‘ && c>=‘0‘ ? true : false; 
    }

}
View Code

 

String to Integer

原文:http://www.cnblogs.com/sunshisonghit/p/4462148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!