算法——字符串转化为32位有符号整数atoi()

2022-3-5 diaba 算法

package com.jiucaiyuan.net.algrithm.sum;

/**
 * 将一个字符串转化为32位有符号整数,(类似C/C++中的atoi函数)
 *
 * @author jiucaiyuan on 2022/3/5.
 */
public class MyAtoi {
    public static int myatoi(String s) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        //去掉空格的情况
        int index = 0;
        while (index < len && chars[index] == ' ') {
            index++;
        }
        // 排除极端情况,例如:"    "
        if (index == len) {
            return 0;
        }

        // 设置符号
        int sign = 1;
        char firstChar = chars[index];
        if (firstChar == '-') {
            index++;
            sign = -1;
        } else if (firstChar == '+') {
            index++;
        }

        //last,用于记录上一次的res,以此来判断是否溢出的情况
        int res = 0, last = 0;
        while (index < len) {
            char c = chars[index];
            if (c < '0' || c > '9') {
                break;
            }
            int tem = c - '0';
            last = res;
            res = res * 10 + tem;

            //如果不相等就是溢出了
            if (last != res / 10) {
                return (sign == (-1)) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            index++;
        }
        return res * sign;
    }

    public static void main(String[] args) {
        String source1 = "42";
        int target1 = myatoi(source1);
        System.out.println(source1 + ":" + target1);

        String source2 = "-42";
        int target2 = myatoi(source2);
        System.out.println(source2 + ":" + target2);

        String source3 = "4193 with words";
        int target3 = myatoi(source3);
        System.out.println(source3 + ":" + target3);
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022