Ritual Algorithm Mathematics Class - Converting Strings to Integers

Table of contents

string to integer

answer:

code:

Optimized code:


string to integer

8. Convert String to Integer (atoi)

Please implement a  myAtoi(string s) function that converts a string into a 32-bit signed integer (similar to  atoi the function in C/C++).

The algorithm of the function  myAtoi(string s) is as follows:

  1. Read in a string and discard useless leading whitespace
  2. Checks whether the next character (assuming the end of the character is not yet reached) is a plus or minus sign, and reads that character (if any). Determines whether the final result is negative or positive. If neither is present, the result is assumed to be positive.
  3. Reads in the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string will be ignored.
  4. Convert these numbers read in by the previous steps to integers (ie, "123" -> 123, "0032" -> 32). If no number is read in, the integer is  0 . Change symbols if necessary (from step 2).
  5. If the number of integers exceeds the range of 32-bit signed integers  [−231,  231 − 1] , the integer needs to be truncated to keep it within this range. Specifically,  −231 integers less than should be fixed to  −231 , and  231 − 1 integers greater than should be fixed to  231 − 1 .
  6. Returns an integer as the final result.

Notice:

  • White space characters in this question include only space characters  ' ' .
  • Do not omit  any characters other than leading spaces or the rest of the string after numbers .

Example 1:

Input: s = "42"
 Output: 42
 Explanation: The bold string is the character that has been read, and the caret is the character that is currently being read.
Step 1: "42" (currently no characters are read because there is no leading space)
         ^
Step 2: "42" (currently no characters are read, because there is no '-' or '+' here)
         ^
Step 3: " 42 " (reads "42")
           ^
Parsing yields the integer 42.
Since "42" is in the range [-231, 231 - 1], the final result is 42.

Example 2:

Input: s = "-42"
 Output: -42
 Explanation: 
Step 1: "    -42" (leading spaces are read, but ignored)
            ^
Step 2: "    - 42" (a '-' character is read in, so the result should be negative)
             ^
Step 3: "    -42 " (reads "42")
               ^
Parsing yields the integer -42.
Since "-42" is in the range [-231, 231 - 1], the final result is -42.

Example 3:

Input: s = "4193 with words"
 Output: 4193
 Explanation:
Step 1: "4193 with words" (currently no characters are read because there are no leading spaces)
         ^
Step 2: "4193 with words" (currently no characters are read, because there is no '-' or '+' here)
         ^
Step 3: " 4193 with words" (read "4193"; since the next character is not a number, the reading stops)
             ^
Parsing yields the integer 4193.
Since "4193" is in the range [-231, 231 - 1], the final result is 4193.

hint:

  • 0 <= s.length <= 200
  • s Consists  of English letters (uppercase and lowercase), numbers ( 0-9), ' ', '+', '-' and '.'

answer:

Determine whether it is empty

remove leading spaces

tentatively positive

signed judgment sign

Determine whether the division sign bit, the first bit is a number

Core code:

while(i < s.length() && s.charAt(i)>='0'&& s.charAt(i)<='9'){
                int temp1=s.charAt(i)-'0';
                if(temp==-1){
                    if(res>214748364||(res==214748364&&temp1>=8)){
                        return -2147483648;
                    }
                }else{
                    if(res>214748364||(res==214748364&&temp1>=7)){
                        return 2147483647;
                    }
                }
                res=res*10+temp1;
                i++;
            }
            return res*temp;  

code:

class Solution {
    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        //去除前导空格
        s=s.trim();
        //暂定结果为正
        int temp=1;
        //检查下一个字符(假设还未到字符末尾)为正还是负号
            //有符号的判断符号
        if(s.length()>0&&(s.charAt(0)=='-'||s.charAt(0)=='+')){
            temp=(s.charAt(0)=='-') ? -1:1;
            s=s.substring(1,s.length());
        }
            //判断除符号位,第一位是不是数字
            if(s.length()<1|| s.charAt(0)<'0'||s.charAt(0)>'9'){
                return 0;
            }
            int i=0;int res=0;          
            while(i < s.length() && s.charAt(i)>='0'&& s.charAt(i)<='9'){
                int temp1=s.charAt(i)-'0';
                if(temp==-1){
                    if(res>214748364||(res==214748364&&temp1>=8)){
                        return -2147483648;
                    }
                }else{
                    if(res>214748364||(res==214748364&&temp1>=7)){
                        return 2147483647;
                    }
                }
                res=res*10+temp1;
                i++;
            }
            return res*temp;            
 }
}

Optimized code:

class Solution {
    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int i = 0;
        int sign = 1;
        int result = 0;

        // 丢弃前导空格
        while (i < s.length() && s.charAt(i) == ' ') {
            i++;
        }

        // 判断符号
        if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++;
        }

        // 转换数字
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            int digit = s.charAt(i) - '0';

            // 检查是否溢出
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
                return (sign == -1) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }

            result = result * 10 + digit;
            i++;
        }

        return result * sign;
    }
}

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/131691941