LeetCode 8 String to Integer (atoi)

原题:(频率5)

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

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



题意:把字符串转化为数字,C++中的atoi函数




代码和思路


//把字符串转换为数字,1:去掉空格,判断格式是否正确 2:判断是否越界,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647)
class Solution {
    public static int myAtoi(String str) {
        
        if (str == null || str.length() == 0){
		    return 0;
        }
        int sign = 1;
        int start =0;
        long sum = 0; 
        //去掉空格
        str = str.trim();  
        //正还是负
        char first = str.charAt(0);      
        if(first=='+'){
          sign = 1;  
          start++;
        }
        else if(first == '-'){
            sign = -1;
            start++;
        }
        
        for (int i = start; i < str.length(); i++) {
        //如果不是数字
		if (!Character.isDigit(str.charAt(i))){
            return (int) sum * sign;
        }
		sum = sum * 10 + str.charAt(i) - '0';
        //判断是否越界
		if (sign == 1 && sum > Integer.MAX_VALUE)
			return Integer.MAX_VALUE;
		if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
			return Integer.MIN_VALUE;
        }
        
        return (int)sum * sign;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值