8. String to Integer (atoi)

来源:互联网 发布:免费视频制作软件知乎 编辑:程序博客网 时间:2024/06/07 19:15

Implement atoi to convert a string to an integer.

public class Solution {    public int myAtoi(String str) {        str = str.trim();        if(str == null || str.length() == 0) return 0;        int res = 0;        int index = 0;        int op = 1;        if(str.charAt(index) == '+') index++;        else if(str.charAt(index) == '-'){            index++;            op = -1;        }        for(; index < str.length(); index++){            int tmp = str.charAt(index) - '0';            if(tmp >= 10 || tmp < 0) break;            int old = res;            res = res * 10 + tmp;            if(res / 10 != old){                if(op == 1) return Integer.MAX_VALUE;                if(op == -1) return Integer.MIN_VALUE;            }        }        return res*op;    }}
0 0
原创粉丝点击