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

前言

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


代码仓库


内容

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

代码(有详细注释)

cdigital.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;
}

编译和运行命令

g++ -o cdigital cdigital.cpp
./cdigital.exe

结果

在这里插入图片描述
在这里插入图片描述


总结

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


参考资料

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

作者的话

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值