tx-lk-中等-1

8. 字符串转换整数 (atoi)

class Solution {
    public int myAtoi(String str) {
/**
         *           ' '    +/-      number    other
         * start     start  signed  in_number   end
         * signed    end    end     in_number   end
         * in_number end    end     in_number   end
         * end       end    end      end        end
         */
        Map<String, String[]> map = new HashMap<>();
        map.put("start", new String[]{"start", "signed", "in_number", "end"});
        map.put("signed", new String[]{"end", "end", "in_number", "end"});
        map.put("in_number", new String[]{"end", "end", "in_number", "end"});
        map.put("end", new String[]{"end", "end", "end", "end"});
        String status = "start";
        int ans = 0;
        int signed = 1;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String[] ss = map.get(status);
            status = ss[getIndex(c)];
            //要转为整型
            int cc = c - 48;
            if (status.equals("in_number")) {
                // 注意,ans * 10 + cc>Integer.MAX_VALUE的变形
                if (ans > (Integer.MAX_VALUE - cc) / 10) {
                    if (signed == 1) {
                        return Integer.MAX_VALUE;
                    } else {
                        return Integer.MIN_VALUE;
                    }
                }
                ans = ans * 10 + cc;
            } else if (status.equals("signed")) {
                signed = c == '+' ? 1 : -1;

            }
        }
        return signed * ans;
    }
    public static int getIndex(char c) {
        if (c == ' ') {
            return 0;
        } else if (c == '-' || c == '+') {
            return 1;
        } else if (Character.isDigit(c)) {
            return 2;
        } else {
            return 3;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。