String to Integer (atoi)

来源:互联网 发布:在淘宝上怎么买盗版书 编辑:程序博客网 时间:2024/05/16 16:01
public class Solution {    public int myAtoi(String str) {        if (str == null || str.length() == 0) {            return 0;        }        str = str.trim();        boolean positive = true;        int i = 0;        if (str.charAt(i) == '+') {            i++;        } else if (str.charAt(i) == '-') {            i++;            positive = false;        }        long num = 0;        for (; i < str.length(); i++) {            char c = str.charAt(i);            if (c < '0' || c > '9') {                break;            }            if (positive){                num = num*10 + (c - '0');                if(num >= Integer.MAX_VALUE) {                    return Integer.MAX_VALUE;                }             } else {                num = num*10 - (c - '0');                if (num <= Integer.MIN_VALUE) {                    return Integer.MIN_VALUE;                }            }        }        return (int)num;    }            // 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
原创粉丝点击