当前位置:网站首页>Sword finger offer 67 Convert a string to an integer

Sword finger offer 67 Convert a string to an integer

2022-07-04 22:45:00 LuZhouShiLi

The finger of the sword Offer 67. Convert a string to an integer

subject

Write a function StrToInt, Realize the function of converting string to integer . Out of commission atoi Or other similar library functions .

First , This function discards the useless start space characters as needed , Until the first non space character is found .

When the first non empty character we find is a positive or negative sign , Then combine the symbol with as many consecutive numbers as possible on the back face , As the sign of the integer ; If the first non empty character is a number , Then combine it directly with the following consecutive numeric characters , Form an integer .

In addition to the valid integer part of the string, there may be extra characters , These characters can be ignored , They should have no effect on functions .

Be careful : If the first non space character in the string is not a valid integer character 、 When the string is empty or the string contains only white space characters , Then your function doesn't need to be converted .

In any case , If the function cannot be effectively converted , Please return 0.

Ideas

  • First delete the space character
  • Sign bit : Create a new variable to save the symbol bit ,‘-’ The sign bit is recorded as 1
  • Nonnumeric character : Encountered the first non numeric character , Go back to
  • Numeric character :
    • Character to number : Subtract... From this character ’0’ that will do
    • Digital stitching : Set the current bit character to c, The current digit is x, The numerical result is res, Then the number splicing formula is :res = res * 10 + c - ‘0’

Code

class Solution {
    
    public int strToInt(String str) {
    
         char[]  c = str.trim().toCharArray();//  Remove space 
        if(c.length ==  0)  return 0;
        int res = 0;
        int bndry = Integer.MAX_VALUE / 10;
        int i = 1,sign = 1;

        if(c[0] == '-') sign = -1;  //  Sign bit 
        else if(c[0] != '+') i = 0;

        for(int j = i; j < c.length; j++)
        {
    
            if(c[j]  < '0' || c[j] > '9')
            {
    
                break;//  Not a digit   Jump straight out of the loop   Then go straight back 
            }
            //  Transboundary 
            if(res > bndry  || res == bndry && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;

            //  Add up 
            res = res * 10 + (c[j] - '0');
        }

        return sign * res;//  Record symbol bit 

    }
}
原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042219387882.html