c++ - c++/c中的基数改变算法

标签 c++

<分区>

我有以下功能:

template <class T>
T c_base (T num,T second, T first = 10)
{
    T res = 0;
    T secnum;
    T bitseed[90];
    int i = 1,k,jump,anex,len;
    if(second==first)
    {
        res = num;
        return (res);
    }
    if(first==10&&second!=10)
    {
        anex = num;
        while(num>0)
        {
            jump = num/second;
            bitseed[i] = num%second;
            num/=second;
            i++;
        }
        if(anex>0)
        {
            for(k=i;k>=1;k--)
            {
                if(k==i&&jump==0) {res = bitseed[k-1]; k--; continue;}
                if(k==i&&jump!=0) {res = jump; continue;}
                res = res*10+bitseed[k];
            }
        }
        return (res);
    }

    if(second==10)
    {
        anex = num;
        len = 1;
        while(anex>=10)
        {
            len *= 10;
            anex/=10;
            i++;
        }
        anex = num;
        if(anex>0)
        {
            for(k=i;k>=1;k--)
            {
                res = res*first+anex/len;
                anex%=len;
                len/=10;
            }
        }
        return (res);
    }

    if(second!=10&&first!=10)
    {
        secnum = c_base <T> (num,10,first);
        res = c_base <T> (secnum,second,10);
        return (res);
    }
}

我想知道它的效率如何(从速度和内存消耗的角度来看)以及如何/是否可以改进它。 (从算法角度)

附言。函数说明:c_base("number","to-base","from-base"->optional);

最佳答案

我在这里看到了很多困惑:

  • 数字没有底数。有基础的是数字表示。输入和输出都应该是数字表示(例如 C++ 中的 std::strings)。
  • 为什么要特别处理基数 10?它没有什么特别之处,只是由于历史事故,今天大多数人都在使用它。这与算法完全无关。出于技术原因,以 2 为基数的幂的特殊情况可能有意义(因为计算机在内部使用基数 2)。
  • 为什么要进行双重转换而不是仅仅从基数 x 读取并写入基数 y

关于c++ - c++/c中的基数改变算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20172738/

相关文章:

c++ - C++在内部声明变量时如何生成随机地址?为什么它不线性存储它们?

c++ - 监听来自 C++ Q_OBJECT 的附加 Component.onCompleted 和 Component.onDestroyed 信号

python - "Cannot convert Python object argument to type ' <typename> '"- 使用 Cython 包装 C++ 类时出错

c++ - 我应该返回指向数组或特定元素开头的指针吗?

c++ - 有没有办法让 midl 在单独的 .h 中生成每个接口(interface)?

c++ - 任意类型上的 GDB 条件断点,例如 C++ std::string 相等性

java - 什么是好的免费游戏引擎?

C++:模板代码在 clang++ 下编译和运行良好,但在 g++ 下失败

c++ - 如何解释 sizeof(std::vector<int>) 的值?

c++ - x = malloc(n * sizeof (int));无法将 void 转换为 int