您的位置:首页 > 其它

leetcode第8题——*String to Integer (atoi)

2016-01-01 11:07 344 查看

题目

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.

思路

题目大意是将字符串转换为整型,分正负数的情况,忽略空白字符和非数字字符,比如:“ -1234a”转换为-1234,"jsk903"转换为903,"2345678"转为2345678......如果超出整型数据范围则取0x7FFFFFFF或0x80000000. 题目本身很简单,先将空字符和符号位取出,然后依次将每位上的结果乘以10再加入到新的结果中。要注意的是溢出处理,可以定义一个长整型变量res保存结果,如果res超出整型范围则返回0x7FFFFFFF或0x80000000,如果没有超出则将res转换为整型再返回即可。

代码

Python

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        strLen = len(str)
        if str == '':
            return 0
        i = 0
        
        while (i < strLen):
            #跳过空白字符
            if(str[i] == ' '):
                i += 1
            else:
                break

        if i == strLen:
            return 0
        signal = 1
        if str[i] == '+':
            signal = 1
            i += 1
        elif str[i] == '-':
            signal = -1
            i += 1

        res = 0
        #Python不声明变量类型,数字超出int型范围自动转为长整型,因此要在80000000前加负号
        maxInt = 0x7FFFFFFF
        minInt = -0x80000000
        
        while (i < strLen):
            if ((str[i] >= '0') & (str[i] <= '9')):
                #是数字则乘以权值并相加
                res = res*10 + signal*(int(str[i]))
            else:
                return res
            #这里可加语句用来调试print 'str[%d]=%s,res=%d'%(i,str[i],res)
            if(res > maxInt):
                return maxInt
            elif(res < minInt):
                return minInt
            i += 1;
                
        return res


Java

public class Solution {
    public int myAtoi(String str) {
        int strLen = str.length();
		if (str == "") return 0;
		int i = 0;
		
		while (i < strLen){
			if(str.charAt(i) == ' ') i++;
			else break;
		}
		if (i == strLen) return 0;
		int signal = 1;
		if (str.charAt(i) == '+'){
			signal = 1;
			i++;
		}
		else if (str.charAt(i) == '-'){
			signal = -1;
			i++;
		}
		long res = 0;
		int maxInt = 0x7FFFFFFF;
		int minInt = 0x80000000;
		while (i < strLen){
			if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
				//是数字则乘以权值并相加
				res = res*10 + signal*(str.charAt(i) - '0');
			}
			else return (int)res;
			if (res > maxInt || res < minInt)
				return res>0?maxInt:minInt;
			i++;
		}
		return (int)res;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: