【Leetcode】String to Integer(ATOI)

27 篇文章 0 订阅
14 篇文章 0 订阅

【题目】

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

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.

【思路】

需要注意考虑的情况有很多很多,string的话可以是 空格 ,可以是其他的字符,需要进行判断。

string开始的时候可能有很多空字符,那么首先就是要去空字符,一直循环到不是“ “的时候停止。

然后出现的第一个有效的字符应该是符号字符。”+“, ”-“

出现字符的时候,要判断下一个紧接着是不是数字,如果不是数字,直接返回错,因为根本就不是一个正常的数字.

判断已有的结果是否已经达到了最大值/10, 或者等于最大值除以10,并且下一个数字>8,就根据正负号返回最大或者最小值,否则就继续添加下一个数字。

步骤 :

1. 去空字符

2. 符号字符

3. 判断溢出


最后返回带有符号的结果。


【代码】

public class Solution {
    public int atoi(String str) {
     
 		final int INT_MAX=Integer.MAX_VALUE;
		final int INT_MIN=Integer.MIN_VALUE;
		  if(str.length() == 0)
	            return 0;
	        int i=0;
	        int flag = 1;
	        int tmp = 0;
	        while(str.charAt(i)==' ')
	            i++;
	        
	        if(str.charAt(i) == '+'||str.charAt(i) == '-'){
	         if(!(str.charAt(i+1) >= '0' && str.charAt(i+1) <= '9')) return 0;
	         if(str.charAt(i) == '-')
	        {
	            flag = -1;
	        }
	         i++;
	        }
	        while (i<str.length()&&str.charAt(i) >= '0' && str.charAt(i) <= '9') {
	            if (tmp >  INT_MAX / 10 || (tmp == INT_MAX / 10 && str.charAt(i) - '0' > 7)) {
	                if (flag == 1) return INT_MAX;
	                else return INT_MIN;
	            }
	            tmp  = 10 * tmp + (str.charAt(i++) - '0');
	        }
	        return tmp*flag;    
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值