[LeetCode8] String to Integer (atoi)

本文详细解析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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

As there is no need to consider float number, what we need concern here is
(1) "+" and "-"
(2) The boundary INT_MAX and INT_MIN
(3) Eliminate the spaces before.
(4) Meet non-digit after digit then return. 

Java

public int atoi(String str) {
        int result =0;
		int sign = 1;
		int startIndex = 0;
		int len = str.length();
		int max = 2147483647;
		if(str.length()<=0) return 0;
		while(str.charAt(startIndex)==' '&&startIndex<len) startIndex++;
		if(str.charAt(startIndex)=='+') startIndex++;
		if(str.charAt(startIndex)=='-') {
			sign = -1;
			startIndex++;
		}
		for(;startIndex<len;startIndex++){
			if(str.charAt(startIndex)<'0'||str.charAt(startIndex)>'9') break;
			if(max/10<result||(max/10==result && max%10<(str.charAt(startIndex)-'0'))){
				return sign==1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;
			}
			result = result*10+(int)(str.charAt(startIndex)-'0');
//			System.out.println(str.charAt(startIndex)-'0');
		}
		return result*sign;
    }

leetcode 又更新了 test cases, 比如“+-21”这种情况。
Refactor: 09/23/2014
public int atoi(String str) {
        if(str.length()<=0) return 0;
		int result = 0;
		int sign = 0;
		int startIndex = 0;
		while(startIndex<str.length() && str.charAt(startIndex)==' ') startIndex++;
		if(startIndex==str.length()) return 0;
		if(str.charAt(startIndex)=='+') {
			sign=1;
			startIndex++;
		}
		if(str.charAt(startIndex)=='-'){
			if(sign==1) return 0;
			sign = -1;
			startIndex++;
		}
		for(;startIndex<str.length();startIndex++){
			if(str.charAt(startIndex)<'0' || str.charAt(startIndex)>'9') break;
			else if((Integer.MAX_VALUE/10<result)||(Integer.MAX_VALUE/10==result && Integer.MAX_VALUE%10<str.charAt(startIndex)-'0')){
				return (sign==1 || sign==0) ? Integer.MAX_VALUE: Integer.MIN_VALUE;
			}else {
				result = result*10 + str.charAt(startIndex)-'0';
			}
		}
		return sign==-1 ? result*sign: result;
    }


C++

int atoi(const char *str) {
        int num=0;
    int sign = 1;
    int len = strlen(str);
    int i=0;
    while(str[i]==' ' && i<len) i++;
    if(str[i] == '+') i++;
    if(str[i] == '-') {sign =-1; i++;}
    for(;i<len;i++){
        //if(str[i]==' ') break;
        if(str[i]<'0' || str[i] > '9') break;
        if(INT_MAX/10 < num || INT_MAX/10 == num && INT_MAX%10 < (str[i]-'0')){
            return sign == -1 ? INT_MIN : INT_MAX;
            break;
        }
        num = num*10 + str[i] - '0';
    }
    return num*sign;
    }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值