leetcode-8.字符串转换为数字

题目:https://leetcode-cn.com/problems/string-to-integer-atoi/

答案:字符串 

public int myAtoi(String str) {

  str = str.trim();

        int len = str.length();

        if(len==0) return 0;

        char[] chars = str.toCharArray();

        boolean negative = false;

        int index = 0;

        if (chars[index] == '-') {

            negative = true;

            index++;

        } else if (chars[index] == '+') {

            index++;

        } else if (!Character.isDigit(chars[index])) {

            return 0;

        }

        int ans = 0;

        while (index < len && Character.isDigit(chars[index])) {

            int digit = chars[index] - '0';

            if (ans > (Integer.MAX_VALUE - digit) / 10) {

                return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;

            }

            ans = ans * 10 + digit;

            index++;

        }

        return negative? -ans : ans;

    }

猜你喜欢

转载自blog.csdn.net/wuqiqi1992/article/details/108366342