8. String to Integer (atoi)

来源:互联网 发布:js的单选按钮的事件 编辑:程序博客网 时间:2024/06/05 14:23

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

问题描述:atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,注意整数溢出问题。

分析:输入的字符串有以下几种情况考虑:

(1)当输入的字符串长度为0或者去掉空格后长度为0时,返回0;

(2)当输入的字符串第一个字符为“+”、“-”,变量flag记录转换后的整数符号。为“+”时,flag=1;为“-”时,flag=-1;

(3)当字符为数值时,即(s.charAt(i) - '0')>=0 && (s.charAt(i) - '0')<=9,变量result记录转换后的整数,result = result*10+s.charAt(i) - '0';循环字符串,直到字符不为数字时结束循环;

(4)当整数溢出时,即result*flag>Integer.MAX_VALUE时,返回Integer.MAX_VALUE;result*flag<Integer.MIN_VALUE时,返回Integer.MIN_VALUE。

public class Solution {    public int myAtoi(String str) {        String s = str.trim();        if(s.length() == 0){            return 0;        }        int flag = 1;        int result = 0;        for(int i=0;i<s.length();i++){            if(i == 0){                if(s.charAt(0) == '+'){                    flag = 1;                }else if(s.charAt(0) == '-'){                    flag = -1;                }else if((s.charAt(0) - '0')>=0 && (s.charAt(0) - '0')<=9){                    result = s.charAt(0) - '0';                }else{                    return 0;                }            }else if((s.charAt(i) - '0')<0 || (s.charAt(i) - '0')>9){                break;            }else{                 if(Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE %10 < (s.charAt(i)-'0'))                    return flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;                 result = (result*10)+(s.charAt(i)-'0');            }        }        return result*flag;    }}