• 剑指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] = '';
    
        while (!Increment(number))
            PrintNumber(number);
    
        delete[]number;
    }
  • 相关阅读:
    字符乱码问题
    一个利用go反向代理解决api转发的例子(go反向代理)
    udp绑定信息
    python3编码转换(字符串/字节码)——Python
    网络UDP——Python
    常用服务器ftp、ssh——Python
    Linux寻找国内镜像源——Python
    常用 Linux 命令的基本使用(二)——Python
    Linux 主要目录速查表——Python
    飞机大战——Python
  • 原文地址:https://www.cnblogs.com/chengxuyuanxiaowang/p/4348435.html
Copyright © 2020-2023  润新知