LeetCode进阶之路(Reverse Integer)

本文介绍了一个将字符串转换为整数(atoi)的Java实现方法,并详细解释了如何处理边界情况,例如符号位、非数字字符及越界等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

又是一道充满坑的题目

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.

把字符串转成int,有几个点需要注意:

1.超出int范围;

2.+-需要另外考虑,表示符号,之后第二个出现非数字,就结束;

3.开始的空格需要忽略,从第一个字符开始考虑;

public static int myAtoi(String str) {
		List<Integer> list = new ArrayList<Integer>();
        str = str.trim();//除去收尾的空格
        int k = 0;
        int l = 0;
        double sum = 0;
        int isNagetive = 1;
        for(int i = 0;i < str.length(); i++) {
            try{
        	if(str.charAt(i)=='-'){
                        isNagetive = -1;
            		k++;//统计出现的‘-’
            	}else if(str.charAt(i) == '+'){
            		l++;//统计出现的‘+’
            	}else if(k>1){
            		break;//减号出现两次,结束循环;
            	}else if(l>1){
            		break;//加好出现两次,结束循环;
            	}else if(l>0 && k>0){
            		break;//加减各出现一次,也结束循环
            	}else if(Integer.parseInt(str.charAt(i)+"")>=0 && Integer.parseInt(str.charAt(i)+"")<=9) {
            		list.add(Integer.parseInt(str.charAt(i)+""));
            	}
        	}catch(Exception e){
        		break;//出现既不是加好减号,也不是数字的字符,结束循环;
        	}
        	
        }
        for(int i = 0;i < list.size();i++) {
        	sum = sum*10 + list.get(i);
        }
        sum = sum*isNagetive;
        
        if(sum > Integer.MAX_VALUE) {
        	return Integer.MAX_VALUE;
        }
        
        if(sum < Integer.MIN_VALUE) {
        	return Integer.MIN_VALUE;
        }
        
        return (int)sum;
    }
代码很简单,但是问题一开始考虑不周全,提交了很多次才正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值