LeetCode-String to Integer (atoi)

来源:互联网 发布:玛泽会计师事务所 知乎 编辑:程序博客网 时间:2024/05/17 09:01
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24427947
时间:2014-4-24

题目

String to Integer (atoi)

 Total Accepted: 9005 Total Submissions: 62173My Submissions

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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

public class Solution {    public int atoi(String str) {            }}


解法

public class Solution {    public int atoi(String str) {        int flag= 1;        long num = 0;        int index = 0;        int len = str.length();        int add=0;        char c;        int  INT_MAX=2147483647;        int  INT_MIN = -2147483648;        boolean change = false;        if(len==0)            return 0;        while(index<len){            // filter            c=str.charAt(index++);            if(c=='-'&& !change)            {                flag = -1;                change = true;            }            else if(c=='+'&& !change){                flag = 1;                change = true;            }            else if(c>='0'&&c<='9'){            //else if(c==0x9){                add = c - '0';                change = true;            }            else if(c==' '&& !change)                ;            else                break;            //excute                            if(Integer.MAX_VALUE/10 >= num)                num *= 10;            else                return (flag==1)?INT_MAX:INT_MIN;                            if(Integer.MAX_VALUE-num>=add)                num += add;            else                return (flag==1)?INT_MAX:INT_MIN;                    }                return flag*((int)num);    }}

返回

LeetCode Solution(持续更新,java>c++)


0 0
原创粉丝点击