zoukankan      html  css  js  c++  java
  • 数制转换

    /*******************

    Base Transform

    ******************
    */
    #include
    <iostream>
    #include
    <cstring>
    #include
    <string>

    using namespace std;

    string str;
    int start[1000],ans[1000],res[1000];//被除数,商,余数

    //转换前后的进制
    int oldBase,newBase;

    int change()
    {
    //各个数位还原为数字形式
    int len=str.length();
    start[
    0]=len;
    for(int i=0;i<=len;i++)
    {
    if(str[i] >= '0' && str[i] <= '9')
    {
    start[i
    +1] = str[i] - '0';
    if(start[i+1]>=oldBase)
    {
    cout
    <<"input error!"<<endl;
    return -1;
    }
    }
    if(str[i] >= 'a' && str[i] <= 'f')
    {
    start[i
    +1] = str[i] - 'a' + 10;
    if(start[i+1]>=oldBase)
    {
    cout
    <<"input error!"<<endl;
    return -1;
    }
    }
    if(str[i] >= 'A' && str[i] <= 'F')
    {
    //大小写同时支持
    start[i+1] = str[i] - 'A' + 10;
    if(start[i+1]>=oldBase)
    {
    cout
    <<"input error!"<<endl;
    return -1;
    }
    }
    }
    return 1;
    }

    void solve()
    {
    memset(res,
    0,sizeof(res));//余数初始化为空
    int y,i,j;

    while(start[0] >= 1)//
    {
    y
    =0;
    i
    =1;
    ans[
    0]=start[0];

    while(i<=start[0])
    {
    y
    =y*oldBase+start[i];
    ans[i
    ++]=y/newBase;
    y
    %=newBase;
    }
    res[
    ++res[0]] = y;//这一轮运算得到的余数
    i = 1;
    //找到下一轮商的起始处
    while((i<=ans[0]) && (ans[i]==0)) i++;
    //清除这一轮使用的被除数
    memset(start,0,sizeof(start));
    //本轮得到的商变为下一轮的被除数
    for(j = i;j <= ans[0];j++)
    start[
    ++start[0]] = ans[j];
    memset(ans,
    0,sizeof(ans));
    //清除这一轮的商,为下一轮运算做准备
    }
    }

    void output()
    {
    //从高位到低位逆序输出
    int i;
    cout
    <<"output:";
    for(i = res[0];i >= 1;--i)
    {
    if(res[i]>=10&&res[i]<=15)//输出为大写字母
    cout<<(char)(res[i]-10+'A');
    else
    cout
    <<res[i];
    }
    cout
    <<endl;
    }

    int main(int argc, char *argv[]) {
    cout
    <<"conversion"<<endl;
    cout
    <<"oldBase:";
    cin
    >>oldBase;
    cout
    <<"newBase:";
    cin
    >>newBase;
    while(1)
    {
    cout
    <<"input:";
    cin
    >>str;
    if(change()==1)
    {
    solve();
    output();
    cout
    <<"'q' to quit,any other key to continue:";
    cin.
    get();
    if(cin.get()=='q')
    break;
    }
    }
    return 0;
    }

  • 相关阅读:
    子网掩码
    IP详解
    TCP/IP模型和OSI模型的对应
    Nginx模块之请求限制
    Nginx中的压力测试工具
    Nginx服务器的处理机制
    算法笔记-动态规划
    算法笔记-分治法
    算法笔记-贪心算法
    算法笔记-乱七八糟问题
  • 原文地址:https://www.cnblogs.com/bl4nk/p/2023081.html
Copyright © 2011-2022 走看看