【LeetCode】7 & 8

7 - Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Notice:

1.If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

2.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

3.For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

int reverse(int x)
{
    long long num=x;    //To avoid overflow
    long long result=0;
    int sign=1;
    if(num<0){
        sign=-1;
        num=-num;
    }
    while(num!=0){
        result=result*10+num%10;
        num/=10;
    }
    if(result>INT_MAX){
        if(result==INT_MAX+1&&sign==-1)return INT_MIN;
        else
            return 0;
    }
    return result*sign;
}
 

8 - String to Integer

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.

Tips:

 1. Input:"+-2" Output:-2 Expected:0  

2. Each time input str[i], it needs to judge if overflow happened, the number may exceed either long or long long

int myAtoi(string str)
{
    if(str.size()==0)return 0;
    int i=0,flag=1;
    while(str[i]==' ')i++;
    if(str[i]=='-'||str[i]=='+')
    {
        if(str[i]=='-')flag=-1;
        i++;
    }
    if(str[i]>'9'||str[i]<'0')return 0;
    long long temp;
    for(int j=i;j<str.size();j++)
    {
        if(str[j]>'9'||str[j]<'0')break;
        temp=temp*10+(str[j]-'0');
        if(flag==1 && temp>INT_MAX)
            return INT_MAX;
        else if(flag==-1 && temp>INT_MAX)
            return INT_MIN;
    }
    return (int)(temp*flag);
}
原文地址:https://www.cnblogs.com/irun/p/4681332.html