字符串转整数

题目来源

代码实现:

package Algorithms;

/**
 * @author : zhang
 * @version : 1.0
 * @date : Create in 2021/7/26
 * @description :
 */
public class StrToInt {
    public static void main(String[] args) {
        String s = "  123yy";
        int myint = myAtoi(s);
        System.out.println(myint);
    }

    public static int myAtoi(String s) {
        int len = s.length();
        //将字符串转化为字符数组
        char[] charArray = s.toCharArray();

        //1、去除前导空格
        int index = 0;
        while (index < len && charArray[index] == ' ') {
            index++;
        }

        //2、如果已经遍历完成(针对极端用例 "     ")
        if (index == len) {
            return 0;
        }

        //3、如果出现符号字符,仅第1个有效,并记录正负
        int sign = 1;
        char firstChar = charArray[index];
        if (firstChar == '-') {
            index++;
            sign = -1;
        }

        //4、将后续出现的数字字符进行转化
        //不能使用long类型(题目规定)
        int res = 0;
        while (index < len) {
            char currChar = charArray[index];
            //先判断不合法的情况 如"+-42"
            if (currChar > '9' || currChar < '0') {
                break;
            }

            //题目中说:环境中只能存储32位大小的有符号整数,因此,需要提前判:除以10以后是否越界            
            if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
                return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            //4.2合法的情况下,才考虑转化
            res = res * 10 + currChar - '0';  //ASC 码48 就是'0',也就是说'0'的值为48,而后依次是'1'到'9',char型减去48就是它对应的int值
            index++;
        }
        return sign > 0 ? res : sign * res;
    }
}
原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/15063641.html