LeetCode题解:String to Integer (atoi)

来源:互联网 发布:怎么找m2c 厂商 知乎 编辑:程序博客网 时间:2024/05/16 09:16

Implement atoi to convert a string to an integer.

题意:把字符串转换为整数

解决思路:按照整数的限制一个个转换字符串的每一个字符

代码:

public class Solution {    public int myAtoi(String str) {        int sign = 1;        int total = 0;        int index = 0;        if(str.length() == 0){            return 0;        }        while(str.charAt(index) == ' ' && index < str.length()){            index++;        }        if(str.charAt(index) == '+' || str.charAt(index) == '-'){            sign = str.charAt(index) == '+'? 1 : -1;            index++;        }        while(index < str.length()){            int digit = str.charAt(index) - '0';            if(digit < 0 || digit > 9){                break;            }            if(Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit){                return sign == 1? Integer.MAX_VALUE : Integer.MIN_VALUE;            }            total = total * 10 + digit;            ++index;        }        return total * sign;    }}
0 0
原创粉丝点击