stoi转换(罗马,Excel, English words)

String to Integer (atoi)

  • leading whitespace--> s.trim()

  • sign --> '+' or '-'

  • int overflow----> need to check for every iteration

public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        str = str.trim(); //remove trailing space
        
        if (0 == str.length()) return 0;
        int i = 0;
        int sign = 1;
        if (str.charAt(i) == '-') {
            sign = -1;
            i++;
        } else if (str.charAt(i) == '+') {
            i++;
        }
        long num = 0;
        while (i < str.length() && Character.isDigit(str.charAt(i))) {
            num = num * 10 + str.charAt(i) - '0';
            if (num * sign > Integer.MAX_VALUE || num * sign < Integer.MIN_VALUE) {
                return num * sign > Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            i++;
        }
        return (int) num * sign;
    }

Roman to integer

Last updated

Was this helpful?