剑指offer第3章学习:高质量的代码

1.一个很重要的问题,你写代码的时候,变量名称一定要有章法,不能随便起。

2.代码书写尽可能的清晰。

//test 11

double Power_Recursively(double base, unsigned int exponent)

{

    if (exponent == 0)

        return 1;

    

    if (exponent == 1)

        return base;

    

    double result = Power_Recursively(base, exponent >>1);

    

    if (exponent & 0x01 == 1)

        result *= base;

    

    return result;

}

bool equal(double num1, double num2)

{

    if (num1 - num2 <= 0.0000001&&num1 - num2 >= -0.0000001)

        return true;

    else

        return false;

}

bool g_InValidInput = false;

double Power(double base, int exponent)

{

    

    g_InValidInput = false;

    if (equal(base, 0.0) && exponent == 0)

    {

        g_InValidInput = true;

        return 0.0;

    }



    unsigned int AbsExponent = (unsigned int)exponent;

    if (exponent < 0)

        unsigned int AbsExponent = (unsigned int)(-1 * exponent);



    double result = Power_Recursively(base, AbsExponent);



    return result;

}
//test 12 打印1到最大的n位数

bool Increment(char* number)

{

    bool IsOverflow = false;

    int nTakeOver = 0;

    int nLength = strlen(number);//得到字符串的长度



    for (int i = nLength - 1; i >= 0; --i)//从字符串的最后一位向前判断

    {

        int nSum = number[i] - '0' + nTakeOver;

        if (i == nLength - 1)

            nSum++;

        if (nSum >= 10)

        {

            if (i == 0)

                IsOverflow = true;

            else

            {

                nSum -= 10;

                nTakeOver = 1;

                number[i] = '0' + nSum;

            }

        }

        else

        {

            number[i] = '0' + nSum;

            break;

        }

    }

    return IsOverflow;

}



void PrintNumber(char* number)

{

    bool IsBeginning0 = true;

    int nLength = strlen(number);

    for (int i = 0; i < nLength; ++i)

    {

        if (IsBeginning0&&number[i] != '0')

            IsBeginning0 = false;

        if (!IsBeginning0)

            cout << number[i];

    }

}

void Print1toMaxOfDigits(int n)

{

    if (n <= 0)

        return;

    char *number = new char[n + 1];

    memset(number, '0', n);

    number[n] = '\0';



    while (!Increment(number))

        PrintNumber(number);



    delete[]number;

}

你可能感兴趣的:(学习)