算法第六次作业

来源:互联网 发布:什么商品淘宝禁止出售 编辑:程序博客网 时间:2024/06/10 21:39

这里首先写一个我遇到到的一个问题

while(i<n&&str[i]>='0'&&str[i]<='9')        {           if(base>INT_MAX/10||(base==INT_MAX/10&&str[i]-'0'>7))           {return (sign==1)?INT_MAX:INT_MIN;}         base=10*base+(str[i++]-'0');        }

在base==INT_MAX/10&&str[i]-‘0’>7这句话中如果把==错打成=,会有很神奇的事情发生
这里写图片描述
我反复调试base的赋值语句,终于找到了跟它毫不相干的错误!
错误原因:每次if判断时候base会溢出,base归零,所以base输出值为最后一位3
以下是正文
题目:
8. String to Integer (atoi)
DescriptionHintsSubmissionsDiscussSolution
Discuss Pick One
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.

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.
解析:这里就考验大家的英语阅读理解了,其实很多题都是这样,要仔细分析题目给出的条件,尽可能的想得全面,本题有以下条件

  1. 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,如果没有,则该字符串是空的,则返回0.

  2. 若第一个非空格字符是符号+/-,则标记sign的正负,后面再有+/-也不要紧,因为后面如果不是数字那么我们将base赋值为0,0乘以所有数都为0,最后是一样的

  3. 如果下一个字符是数字,则转为整形存下来,若接下来再有非数字出现,则返回目前的结果。这里我们利用ascii码‘0’与‘9’判断。

  4. 还需要考虑边界问题,如果超过了整形数的范围,则用边界值替代当前值。

以下是代码:

class Solution {public:    int myAtoi(string str) {        if(str.empty())            return 0;int base=0;        int sign=1;        int n= str.length();        int i=0;        while(i<n&&str[i]==' ')            i++;        if(str[i]=='+'||str[i]=='-')            sign=(str[i++]=='+')?1:(-1);        while(i<n&&str[i]>='0'&&str[i]<='9')        {           if(base>INT_MAX/10||(base=INT_MAX/10&&str[i]-'0'>7))           {return (sign==1)?INT_MAX:INT_MIN;}         base=10*base+(str[i++]-'0');        }        return base*sign;    }};
原创粉丝点击