C++ 进制转换

进制转换是一类常见的代码笔试面试问题,在实际的工程应用中,也是一类常需要处理的步骤。

这类问题在笔试中通常考察的是对代码的输入输出相关操作的熟悉程度。考察能否正确读取测试用例,并转换为正确的输出格式,是一类较为基础的问题。

输入输出

C++提供了多种输入输出命令。
在标准命名空间下,常用的输入输出命名为

using namespace std;
cin;//读取数据
cpit;//输出数据
cerr;//输出错误信息到标准错误流
clog;//用于输出日志到标准错误流

一般来说上述命令就已经足够,这对不同问题也可以去找行相应的函数。
我们这里使用getline来读取测试用例。该命令可以从输入流中读取一行字符串。

getline(cin, name)//从标准输入读取一行字符串。

具体实现

我们以16进制转换为10进制作为示例

#include <iostream>
#include <string>
#include <cmath>

using namespace std;
class C_HexConverter{
public :
    int to_decimal(const string &hexStr){
        int decimal_value=0;
        //读取字符串,并按照读取的字符转化为十进制数字
        int len = hexStr.size();
        for(int i = 0; i < len; i++)
        {
            char ch = hexStr[i];
            int digit;
            if(ch>='0' && ch<='9'){
                digit = ch - '0';
            }
            if(ch >= 'A' && ch <= 'F'){
                digit = ch - 'A' + 10 ;
            }
            if(ch >= 'a' && ch <= 'f'){
                digit = ch - 'a' + 10 ;
            }
        decimal_value += digit*pow(16,len-i-1);
        }
       
        return decimal_value;
    }

};


int main() {
    string s;
    C_HexConverter hex_converter;
    while (getline(cin, s)) { // 注意 while 处理多个 case
        int decimal_value = hex_converter.to_decimal(s);
        cout<<decimal_value<<endl;
    }
    return 0;
}

其他进制转换为10进制的思路相同。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CCC_bi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值