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;
    }
    
  • 相关阅读:
    php 数组分页
    Fchart
    thinkphp对数据库操作有哪些内置函数
    MySQL性能优化的最佳20+条经验
    apache 简单笔记
    PHPMyadmin 配置文件详解(配置)
    mysql 常用知识
    分布式微服务日志的配置
    分布式微服务的配置
    分布式接口的调用
  • 原文地址:https://www.cnblogs.com/myblog1993/p/11458189.html
Copyright © 2011-2022 走看看