C++代码示例:进制数简单生成工具

前言

C++代码示例:进制数简单生成工具。


代码仓库


内容

  • 简单地生成进制数
  • 有详细的步骤解析

代码(有详细注释)

cdigital.cpp

cpp 复制代码
#include <vector>
#include <iostream>

using std::cout;
using std::endl;
using std::vector;

class CDigital
{

public:
    CDigital(const vector<int> &bases) : bases(bases), curDig(0), digCount(0) {}

    bool next()
    {
        // 第一次进入初始化当前组合,如bases.size()=3,this->curDig为000,从000开始遍历
        if (this->curDig.empty() == true)
        {
            this->curDig.resize(bases.size(), 0); // 初始化所有位置为0

            ++this->digCount;
            return true;
        }

        // 1. 从后向前找到第一个不是该位置最大值的位置,
        int curPos = bases.size() - 1;
        while ((curPos >= 0) && (this->curDig.at(curPos) == this->bases.at(curPos) - 1)) // 是最大值就移动位置
        {
            --curPos;
        }

        if (curPos < 0)
        {
            return false; // 都是最大位置,组合结束
        }

        // 2. 然后把该位置数据加1
        ++this->curDig.at(curPos);

        // 3. 最后把后面的各个位置写对应的最小值
        // 一般进制的最小值都为0
        for (int right = curPos + 1; right < this->bases.size(); ++right)
        {
            this->curDig.at(right) = 0;
        }

        ++this->digCount;
        return true;
    }

    inline void printCurDig()
    {
        for (const int d : this->curDig)
        {
            cout << d << " ";
        }
        cout << endl;
    }

    inline void printDigCount()
    {
        cout << this->digCount << endl;
    }

private:
    const vector<int> bases; // 各个位置的进制

    vector<int> curDig; // 当前数字"组合"
    int digCount;       // 数字组合数的数量
};

int main()
{
    const vector<int> bases{4, 5, 3}; // 不同位置的进制数/取值范围 4表示0~3

    CDigital dig(bases);

    while (dig.next())
    {
        dig.printCurDig();
    }
    dig.printDigCount();

    return 0;
}

编译和运行命令

powershell 复制代码
g++ -o cdigital cdigital.cpp
./cdigital.exe

结果


总结

C++代码示例:进制数简单生成工具。


参考资料

  • 学校《高级算法设计与分析》课程课件的算法思路

作者的话

  • 感谢参考资料的作者/博主
  • 作者:夜悊
  • 版权所有,转载请注明出处,谢谢~
  • 如果文章对你有帮助,请点个赞或加个粉丝吧,你的支持就是作者的动力~
  • 文章在描述时有疑惑的地方,请留言,定会一一耐心讨论、解答
  • 文章在认识上有错误的地方, 敬请批评指正
  • 望读者们都能有所收获

相关推荐
郝学胜_神的一滴2 小时前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt00116 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾20 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you21 小时前
constexpr函数
c++
凡人叶枫1 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫1 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss1 天前
BRpc使用
c++·rpc
-森屿安年-1 天前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream1 天前
Cartographer详细讲解
c++·人工智能·自动驾驶