Leetcode 0008-String to Integer(atoi)(字符串转整数)

Leetcode 0008-String to Integer(atoi)(字符串转整数)

题目描述:

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: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) 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 performed.
Example 5:

Input: “-91283472332”
Output: -2147483648
Explanation: The number “-91283472332” is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.

解法一:

class Solution {

    // String to Integer
    public int myAtoi(String str) {
        if(str == null) {
            return 0;
        }
        // 1、去除空格
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        // 2、判断正负    
        int sign = 1;
        int index = 0;
        if (str.charAt(index) == '+') {
            index++;
        } else if (str.charAt(index) == '-') {
            sign = -1;
            index++;
        }
        // 3、将字符串中第一个不为数字的字符之前的字符串转为整数
        long num = 0;
        for (; index < str.length(); index++) {
            if (str.charAt(index) < '0' || str.charAt(index) > '9')
                break;
            num = num * 10 + (str.charAt(index) - '0');
            if (num > Integer.MAX_VALUE ) {
                break;
            }
        }   
        // 4、判断是否溢出
        if (num * sign >= Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (num * sign <= Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int)num * sign;
    }

解法二:

class Solution{
	private static final int INT_MAX = 2147483647;
    private static final int INT_MIN = -2147483648;

    //解题思路:
    //      1、去除空格 str.trim()
    //      2、去除字符串开头的'+' '-',并用flag标记正负 
    //      3、去除字符串中第一个非数字的字符及其之后的所有字符 "1095502006p8" --> "1095502006",此时s由数字组成 
    //      4、去除字符串开头的0   "0000000000012345678"" --> 12345678"
    //      5、判断字符串是否溢出   char[] arr1 = s.toCharArray();char[] arr2 = "2147483647".toCharArray();
    //            * 若字符串s的长度大于字符串"2147483647"的长度,标记溢出isOverflow = true
    //            * 若字符串s的长度等于字符串"2147483647"的长度,遍历字符数组
    //            * 若遇到arr1[i]<arr2[i],跳出循环 即高位字符小于"2147483647"的高位字符,肯定没溢出
    //            * arr1[i] > arr2[i]则标记溢出
     public int myAtoi(String str) {
        if(str == null){
            return 0;
        }
        String s = str.trim();
        if(s.length() == 0){
            return 0;
        }
        int flag = 1;
         
        // 去除 '+' '-',并用flag标记正负
        int index = 0;
        if (s.charAt(index) == '+') {
            index++;
        } else if (s.charAt(index) == '-') {
            flag = -1;
            index++;
        }
        s = s.substring(index, s.length());
        
        if(s.length() == 0){
            return 0;
        }
        // 首字符不为数字
        char[] arr = s.toCharArray();
        if(arr[0] < '0' || arr[0] >'9'){
            return 0;
        }
        
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < arr.length; i ++){
            if(arr[i] < '0' || arr[i] > '9'){
                break;
            }
            builder.append(arr[i]);
        }
        s = builder.toString();// s由数字组成 "0000000000012345678"
        
        // 去除字符串开头的0
        char[] temp = s.toCharArray();
        index = 0;
        while(index < s.length()){
            if(temp[index] > '0'){
                break;
            }
            index ++;
        }
        s = s.substring(index, s.length());
        
        // 判断是否溢出
        char[] arr1 = s.toCharArray();
        char[] arr2 = "2147483647".toCharArray();
        boolean isOverflow = false;
        if(arr1.length > arr2.length){
            isOverflow = true;
        }
        if(arr1.length == arr2.length){
            for(int i = 0; i < arr1.length;i ++){
                if(arr1[i] < arr2[i]){
                    break;
                }
                if(arr1[i] > arr2[i]){
                    isOverflow = true;
                }
            }
        }
        if(isOverflow){
            if(flag == 1){
                return INT_MAX;
            }else{
                return INT_MIN;                
            }
        }
        int res = 0;
        if(s.length() != 0){
            res = flag * Integer.valueOf(s);
        }
        return res;
    }   
}

猜你喜欢

转载自blog.csdn.net/PerryJennings/article/details/83212959