zoukankan      html  css  js  c++  java
  • 算法题----任意进制转换(C++)

    #include <bits/stdc++.h>
    using namespace std;
    
    int toInt(char c)
    {
    //    char c = s;
        if(c >= '0' && c<= '9') return c - '0';
        else if(c >= 'a' && c<= 'z') return c - 'a' + 10;
        else return c - 'A' + 10;
    }
    
    int main()
    {
        int a, b; // a原进制,b转换进制
        cin >> a>> b;
        string str; // 用字符串表示的数字
        cin >> str;
    
        bool negative = false;  // 标记是否为负数,false为正,true为负
    
        if(!str.empty())    // 去掉数字前的所有空格
        {
            str.erase(0,str.find_first_not_of(" "));
        }
    
        if(str[0] == '+')
            str = str.substr(1,str.length() - 1);
        else if(str[0] == '-')
        {
            negative = true;
            str = str.substr(1,str.length() - 1);
        }
    
        int y = 0; // str的十进制表示
        int aa = 1; // 表示每次计算中进制的幂次
        for(int i = str.length() - 1; i >= 0; i--)
        {
            y = y + toInt(str[i]) * aa;
            aa = aa * a;
        }
        string res;
        string tmp;
        do{                       // 此处一定要用do...while(),防止输入是0的情况
            tmp = to_string(y%b) ;
            y = y / b;
            res  = tmp + res;
        }while (y!=0);
    
        if(negative)
            res = '-' + res;
        cout << res << endl;
        return 0;
    }
    
  • 相关阅读:
    linux知识笔记4
    linux知识笔记3
    linux知识笔记2
    linux常用命令笔记1
    计算机网络
    软件测试理论5
    软件测试理论4
    软件测试理论3
    Yarn 常用命令
    mac shell终端编辑命令行快捷键
  • 原文地址:https://www.cnblogs.com/myblog1993/p/11458189.html
Copyright © 2011-2022 走看看