LeetCode题目: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.

这道题目是比较简单的字符串操作题目,但是题目中的坑还是挺多的,不认真做的话很难Accept ,下面贴代码:因为性能分析中运算时间达到了61ms,所以我的代码只适合给新手提供参考,如何提高性能还需要进一步的思考和修改。

class Solution {
    public int myAtoi(String str) {
        
        //先去前后空格,题目中前后有空格也算是有效格式
        str = str.trim();
        String origin  = str;
        if(str.isEmpty()){
            return 0;
        }
        //用StringBuilder来存储字符
        StringBuilder strbuff = new StringBuilder();
	//去掉正负号
        if(str.startsWith("-")||str.startsWith("+")){
            str=str.substring(1);
            System.out.println(str);
        }
        int temp =0;
        //获取数字,遇到非数字则终止
        for(int i=0;i<str.length();i++){
                
                temp = (int)str.charAt(i);
                if(temp>=48&&temp<=57){
                    strbuff.append(str.charAt(i));
                    
                }else{
                    break;
                }
                
            }
        
     
        if(strbuff.length()==0){
            return 0;
        }
        int result = 0;
	使用parseint进行解析,如果超出int值范围则返回Int 的最大值
        try{
           result = Integer.parseInt(strbuff.toString());           
            
        }catch(Exception e){
            if(origin.startsWith("-")){
                return -2147483648;
            }else{
                return 2147483647;
            }
        }
        
        //判断正负
        if(origin.startsWith("-")){
            return 0-result;
        }
        return result;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值