Niuke.com Brushing Questions-Convert a string to an integer

Problem Description

Implement the function atoi. The function of the function is to convert a string to an integer.
Tip: Think carefully about all possible input situations. This question does not give input restrictions, you need to consider all possible situations yourself.

Input description:
input a string

Output description:
the integer of the output string

Example

Example 1

Enter
"123"

Output
123

Solutions

analysis

  1. Through the traversal method of adding and calculating, pay attention to the need to deal with signs and letters, as well as the number of out of bounds.

method

  1. Through the traversal method of adding and calculating, pay attention to the need to deal with signs and letters, as well as the number of out of bounds.

Code

// 思路1
public class Solution {
    
      
    public int atoi(String str) {
    
    
        // write code here
        if (str == null || str.trim().length() < 1)
            return 0;
        //处理掉前后空格
        char[] arr = str.trim().toCharArray();

        int sign = 1, index = 0;
        //判断正负号
        if (arr[0] == '+')
            index++;
        if (arr[0] == '-') {
    
    
            sign = -1;
            index++;
        }

        int num = 0;
        for (int i = index; i < arr.length; i++) {
    
    
            if (arr[i] - '0' >= 0 && arr[i] - '9' <= 0) {
    
    
                //如果当前运算会越界的时候,直接输出结果
                if (num > Integer.MAX_VALUE / 10 || num == Integer.MAX_VALUE / 10 && arr[i] - '7' > 0) {
    
    
                    if (sign > 0)
                        return Integer.MAX_VALUE;
                    else
                        return Integer.MIN_VALUE;
                }

                num = 10 * num + arr[i] - '0';
            } else
                //如果是字母,跳出循环
                break;
        }

        return num * sign;
    }
}

Time complexity analysis:
O(N): Traverse the array

Space complexity analysis:
O(N): additional char array space

If you want to test, you can go directly to the link of Niuke.com to do the test

Convert a string to an integer-niuke.com

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113744253