剑指offer-字符串转数字

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//
 
/*
Q1:
    字符串转数值:
        输入一个数字字符串然后转换为数值。
*/

#include 
#include 
#include 

enum Status {kValid = 0, kInvalid};
int g_nStatus = kValid;

long long strToIntCore(const char*str, bool minus)
{
    long long num = 0;
    while(*str != '\0')
    {
        if(*str >= '0' && *str <= '9')
        {
            int flag = minus?-1:1;
            num = num*10 + flag*(*str - '0');
            if((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000))
            {
                num = 0;
                break;
            }
            str++;
        }else{
            num = 0;
            break;
        }
    }

    if(*str == '\0')
    {
        g_nStatus = kValid;
    }
    return num;
}

long long strToInt(const char*str)
{
    g_nStatus = kInvalid;
    long long num = 0;

    if(str != nullptr && (*str) != '\0')
    {
        bool minus = false;
        if(*str == '+')
            str++;
        else if(*str == '-')
        {
            minus = true;
            str++;
        }

        if(*str != '\0')
        {
            num = strToIntCore(str, minus);
        }
    }
    return num;
}

void test_1()
{
    std::cout << "Test 1" << std::endl;
    std::cout << "12345 = " << strToInt("12345") << " " << g_nStatus << std::endl;
    std::cout << "+12345 = " << strToInt("+12345") << " " << g_nStatus << std::endl;
    std::cout << "-12345 = " << strToInt("-12345") << " " << g_nStatus << std::endl;
    std::cout << "0 = " << strToInt("0") << " " << g_nStatus << std::endl;
    std::cout << "999999999 = " << strToInt("99999999") << " " << g_nStatus << std::endl;
    std::cout << "-99999999 = " << strToInt("-99999999") << " " << g_nStatus << std::endl;
    std::cout << "nullptr = " << strToInt(nullptr) << " " << g_nStatus << std::endl;
}

void test()
{
    test_1();
}

int main(int argc, char**argv)
{

    test();

    return 0;
}

 

你可能感兴趣的:(刷题)