LeeCode-------String to Integer (atoi) 解法

题目如下:


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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.


 

 

大致翻译:


 

实现将字符串转换为整数。

提示:仔细考虑所有可能的输入用例。如果你想要挑战想一下自己,请不要看下面的提示并且自己考虑一下所有可能的输入用例都有哪些。

注意:这个题目故意设置模糊输入(即没有给出输入规范)。你要负责收集并处理所有的输入请求。

更新(2015-02-10):

C++函数的声明已经更新。如果你依然看到你的函数声明接收的是一个 char * 参数,请点击重新加载按钮来重制你的代码定义。


 

 

我们首先考虑的是直接调用Java中String转换为int的函数。

1 public class Solution {
2     public int myAtoi(String str) {
3         try{
4             return Integer.parseInt(str);
5         }catch(Exception e){
6             return 0;
7         }
8     }
9 }

经过测试发现并不能成功提交,因为题目想要我们尽可能多的解析出能够转换的数字。

考虑一下,思想如下:

  1. 是否为空,为空直接返回0;
  2. 从字符串头开始,截取出可以处理的最大字符串长度;
  3. 转换字符串并判断是否越界;
  4. 其他异常情况统一返回0;

【Java代码】如下:

public class Solution {
    public int myAtoi(String str) {
        if(str == null) return 0;
        str = str.trim();
        if(str.length() < 1) return 0;
        int i = 0;
        for(i = 0; i < str.length(); i++){
            if((str.charAt(i) >= '0' && str.charAt(i) <= '9') || str.charAt(i) == '+' || str.charAt(i) == '-') continue;
            else break;
        }
        str = str.substring(0, i);//取前i位符合需求的字符转换
        if(str.length() > 12) str = str.substring(0, 12);//Integer最大为12位,多出部分舍弃掉
        try{
            long res = Long.parseLong(str);//用long来装转换后的数字然后判断是否int越界
            if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            else if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            return (int)res;
        }catch(Exception e){
            return 0;
        }
    }
}

成功提交。

如果有任何问题,欢迎跟我联系:xiaomenxiaomen@qq.com

我的github地址:github.com/WXRain

 

posted @ 2017-07-28 15:51  安忆丶  阅读(104)  评论(0编辑  收藏  举报