8. String to Integer (atoi)

来源:互联网 发布:sql 修改列属性 编辑:程序博客网 时间:2024/06/05 07:48

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.

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

Subscribe to see which companies asked this question

其实可以用stack做

public class Solution {    public int myAtoi(String str) {      int  length=str.length();       int sign =1;        int i = 0 ; long re=0;        while(i<length&&(str.charAt(i)==' '))i++;       if(i==length)return 0;       if(str.charAt(i)=='-'){           sign = -1;       }       if(str.charAt(i)=='-'||str.charAt(i)=='+'){          i++;       }       while(i<length&&str.charAt(i)<='9'&&str.charAt(i)>='0'){           re=re*10+(str.charAt(i)-'0'); i++;             if(re>(long)Integer.MAX_VALUE||re<(long)Integer.MIN_VALUE){           if(sign==1)return Integer.MAX_VALUE;else return Integer.MIN_VALUE;       }       }       if(sign==-1)re=-re;                   return (int)re;    }}

0 0