LeetCode刷题day008 (Jieky)

LeetCode第8题

/*
Implement atoi which converts a string to an integer 

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

Note:
	Only the space character is considered as whitespace character 
	
	Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31 2^31-1]. If the numerical value is out of the range of representable values, INT_MAX (2^31-1) or INT_MIN (-2^31) is returned
	
Example 1: 
Input: "42"
Output: 42

Example 2: 
Input: "-42"
Output:-42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3: 
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4: 
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/-sign. Therefore no valid conversion could be pecformed.

Example 5
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT MIN (-2^31) is returned.
*/

public class StringToInteger{
     
    public static void main(String[] args){
     
        String str1 = "42";
        String str2 = "-42";
        String str3 = "4193 with words";
        String str4 = "words and 987";
        String str5 = "-91283472332";
        String str6 = "99999999999";
        String str7 = "-2147483646";
        String str8 = "+2147483642";
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);

        StringToInteger sti = new StringToInteger();
        int ret = sti.atoi(str7);
        System.out.println(ret);
    }
	
	public int atoi(String s){
     
        // 无效字符串返回0
        if (s == null) return 0;

        //去除字符串两端空格
        String tempStr = s.trim();
		
        // 无效字符串返回0
        if (tempStr.length() == 0) return 0;

        // 将字符串转化为字符数组,获得数组长度
        char[] charArray = tempStr.toCharArray();
		// 有效字符串缓存
        StringBuffer sb = new StringBuffer();

        //非空的第一个字符不是符号,也不是数字
        // 字符可以直接使用 == 判断是否相等,字符可以直接比较字符对应的ascll码
        if (!((charArray[0] == '-') || (charArray[0] == '+') || (charArray[0] >= '0' && charArray[0] <= '9'))){
     
            return 0;
        }else{
     
            sb.append(charArray[0]);
        }

        for (int i = 1;i < tempStr.length();i++){
     
            //遇到非数字字符串,跳出循环
            if (!(charArray[i] >= '0' && charArray[i] <= '9')) break;
            // 正常添加字符
            sb.append(charArray[i]);
        }

        boolean flag = true;
        if (charArray[0] == '-'){
     
			// 定义最大int
            int intMin = 0b10000000000000000000000000000000;
            int len = String.valueOf(intMin).length();
            if (sb.toString().length() > len) return intMin;
			// Integer.parseInt将String转int;Integer.toString将int转String
			// String.valueOf将char[]转String;StringObject.toCharArray()将String转char[]
			// String.valueOf将char转String;StringObject.charAt(index)根据index获得单个字符;
			// Integer.parseInt(CharacterObject.toString())将char转int,charObject - '0'将char转int;(char)(int + '0')将int转char
            if (Integer.parseInt(sb.toString().substring(0,sb.length()-1)) < intMin/10) return intMin;
            if (Integer.parseInt(sb.toString().substring(sb.length()-1,sb.length())) * -1 < intMin%10) return intMin;
        }else{
     
			// 定义最小int
            int intMax = 0b01111111111111111111111111111111;
            int len = String.valueOf(intMax).length();
            if (sb.charAt(0) == '+'){
     
                if (sb.toString().length() > len + 1) return intMax;
            }else{
     
                if (sb.toString().length() > len) return intMax;
            }
            if (Integer.parseInt(sb.toString().substring(0,sb.length()-1)) > intMax/10) return intMax;
            if (Integer.parseInt(sb.toString().substring(sb.length()-1,sb.length())) > intMax%10) return intMax;
        }
        return Integer.parseInt(sb.toString());
    }

}

你可能感兴趣的:(LeetCode,leetcode,java)