String to Integer (atoi)

来源:互联网 发布:网易smtp服务器 端口 编辑:程序博客网 时间:2024/04/27 11:28

一道基本题,当中的确有很多的考点,都是基本功的考察。

我们当中列了6条。

public class Solution {    public int myAtoi(String str) {        // 1. null or empty string        if (str == null || str.length() == 0) {            return 0;        }                // 2. whitespaces          str = str.trim();                // 3. +/- sign          boolean positive = true;        int i = 0;        if (str.charAt(i) == '+') {            i++;        } else if (str.charAt(i) == '-') {            positive = false;            i++;        }                double temp = 0.0;        for (; i < str.length(); i++) {            // 4. invalid character            if (str.charAt(i) > '9' || str.charAt(i) < '0') {                break;            }            int digit = str.charAt(i) - '0';            // 5. handle min & max              if (positive) {                // 6. calculate real value                  temp = temp*10 + digit;                if (temp > Integer.MAX_VALUE) {                    return Integer.MAX_VALUE;                }            } else {                temp = temp*10 - digit;                if (temp < Integer.MIN_VALUE) {                    return Integer.MIN_VALUE;                }            }        }                int result = (int) temp;        return result;    }}


0 0
原创粉丝点击