leetcode--String to Integer (atoi)

本文深入探讨了如何实现字符串到整数的转换算法,详细分析了多种特殊输入情况,并给出了具体的实现步骤。

摘要生成于 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.

思路:题目不是很难,但是有很多特殊输入要考虑

1.数字前面有空格 如s=“    123456”
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0   如s=“   b1234”  ,s=“  ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“   12a12” , s=“ 123  123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648  超过了正数的输出2147483647
public class Solution {
    public int myAtoi(String str) {
        char[] arr = str.toCharArray();
    	long sum = 0;//先用long
    	boolean start = true;//是否为开头(忽略空格)
    	boolean flag = false;//正负号是否出现过
    	boolean positive = true;//数字正负
    	for(int i=0;i<arr.length;i++){
    		if(arr[i]>='0'&&arr[i]<='9'){
    			if(positive&&(sum*10+arr[i]-'0'-Integer.MAX_VALUE)>=0) return Integer.MAX_VALUE;//越界输出最大值
    			if(!positive&&((-(sum*10+arr[i]-'0'))-Integer.MIN_VALUE<=0)){//越界输出最小值				
    				return Integer.MIN_VALUE;
    			}
    			sum = sum*10+arr[i]-'0';
    			start = false;
    		}else if(arr[i]==' ' && start){//忽略开头的空格
    			continue;
    		}else if(arr[i]=='+' || arr[i]=='-'){    			
    		    start = false;
    			if(!flag){//没有出现过正负号
    				flag = true;
    				if(arr[i]=='-') positive=false;
    			}
    			else return 0;//出现过正负号,返回0
    		}else{//除数字,空格,正负号以外,返回之前的数字
    			return (int) (positive?sum:-sum);
    		}
    	}
    	return (int) (positive?sum:-sum);
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值