Sword refers to Offer-46-convert a string to an integer

Title description

To convert a string to an integer, it is required that the library function that converts a string to an integer cannot be used. If the value is 0 or the string is not a legal value, return 0

Enter description:

Enter a string, including alphanumeric characters, can be empty

Output description:

If it is a legal numeric expression, return the number, otherwise return 0.
Example 1

enter

+2147483647
1a33

Output

2147483647
0

Code

Since the code has sufficient comments, it is faster to understand the code directly without writing the ideas.

public class Solution {
    
    
    public int StrToInt(String str) {
    
    
               if(str.length()==0) return 0;
        char[] ch = str.toCharArray();
        //第一个字符可以是正号或者是负号
        int first = 1;//做符号位,1为+,2为-
        int index = 0;//防止出现123这种开始就不是符号位的数字
        if(ch[0] == '-'){
    
    
            //如果是负号且字符串长度不小于1,将符号位置-1
            first ++;
            index++;
        }
        if(ch[0] == '+'){
    
    
            //如果是符号为正号且字符串长度不小于1,将符号位置+1
            index++;
        }
        //在存在符号位的情况下,确定不能只有一个符号位
        if(first!=0&&str.length()==1 ) return 0;
        int result = 0;
        for(int i = index;i<ch.length;i++){
    
    
            if(ch[i]<'0'||ch[i]>'9'){
    
    
                //如果后面的不在0-9的话,说明不是数字
                return 0;
            }
            result = result * 10 + (int)(ch[i]-'0');//-‘0’转换为数字
        }
        if(first == 2) {
    
    
            return result*(-1);
        }else{
    
    
            return result;
        }
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107492972