第26题 String to Integer (atoi)

来源:互联网 发布:安卓手机mac地址怎么查 编辑:程序博客网 时间:2024/05/16 06:18

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.

Solution in c++ 1:

class Solution {public:    int atoi(const char *str) { //指针常量跟常量指针        string input(str);        int length=input.length();        if(length==0) return 0;        int start=0;        while(input[start]==' '){            start++;        }        if(start==length) return 0;                bool neg = false;        long long int sum=0;                      if(input[start]=='-') {neg=true;    start++;}        else if(input[start]=='+') {neg=false;  start++;}                for(;start<length;start++){            int cur=input[start]-'0';            if(cur<0 || cur>9)  break;            int prev= sum;            sum= sum*10 + cur;                        if(neg && -sum<INT_MIN)    return INT_MIN;            if(!neg && sum> INT_MAX)   return INT_MAX;        }        if(neg) sum=(-1)*sum;                return sum;    }};
现在比较新的编译器中long int和int都是4个字节。所以要检查有没有溢出,需要定义sum为long long int。

const char* p 是指向一个常量的指针,即常量指针,指向的内容是常量,但指针p仍是变量。

char* const p 是指针的常量,是不可改变地址的指针,但其所指的内容可以修改。

const char* 和string的转换: const char* str; string convertStr(str);

c++中pow函数第一个参数必须为double


Solution in c++ 2: 这算是作弊吗?

class Solution {public:    int atoi(const char *str) { //指针常量跟常量指针        string input(str);        stringstream ss;        int output=0;        ss<<input;        ss>>output;        return output;    }};


Solution in Java 1: 
public class Solution {    public int atoi(String str) {        String input = str.trim();        if(input.length()==0)   return 0;        String pattern = "^[+,-]?[0-9]+.*";        if(!input.matches(pattern))   return 0;        char[] chs = input.toCharArray();        int index=0;        boolean neg = false;        if(chs[0]=='-'){            neg=true;            index++;        }        else if(chs[0]=='+'){            index++;        }         long  sum=0;        while(index<chs.length){            int cur = chs[index]-'0';            if(cur<0 || cur>9)  break;            sum=sum*10+cur;            index++;            if(!neg && sum>Integer.MAX_VALUE)   return Integer.MAX_VALUE;            else if(neg && -sum< Integer.MIN_VALUE) return Integer.MIN_VALUE;        }        if(neg) sum=(-1)*sum;        int result = new Long(sum).intValue();        return result;            }}

Note: java中没有long long int类型,而long类型为8个字节的整数,足够溢出检查了。
Java中String和char[]转换:String s; char[] chs = s.toCharArray();
Java中String可用正则表达式来检查是否符合某个pattern,函数是s.matches(pattern),pattern也是一个String,通常是正则表达式。
正则表达式中"^"符号表示匹配String的开始,起始端。"?"表示匹配0次或1次,"+"表示匹配1次或多次,"*"表示匹配0次或多次。
整数最大最小值由Integer.MAX_VALUE和Integer.MIN_VALUE获得。

Solution in Java 2:
public class Solution {    public int atoi(String str) {        String input = str.trim();        if(input.length()==0)   return 0;        String pattern = "^[+,-]?[0-9]+.*";        if(!input.matches(pattern))   return 0;        char[] chs = input.toCharArray();        int index=0;        if(chs[0]=='-'||chs[0]=='+')    index++;        while(index<chs.length){            if(chs[index]<'0'||chs[index]>'9') break;            index++;        }        char[] c_res = new char[index];        for(int i=0; i<index; i++)  c_res[i]=chs[i];        String s_res = new String(c_res);        try{            return Integer.valueOf(s_res);        }catch(NumberFormatException e){            if(c_res[0]=='-') return Integer.MIN_VALUE;            else return Integer.MAX_VALUE;        }            }}
Note: Java中char[]转为String:char[] c_res;String s= new String(c_res)或者 String s = String.valueOf(c_res);
String转为int:int result = Integer.valueOf(s);
Java中检查溢出可以catch NumberFormatException。

0 0
原创粉丝点击