蓝桥杯【基础练习】十六进制转八进制

本文介绍了一个从十六进制数转换为二进制数,再从二进制数转换为八进制数的C++实现。该程序通过字符串操作完成转换,并考虑了输入的边界情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要就是16->2然后2->8。

注意不要用函数写,不然会超时。

#include <iostream>
#include <cstring>
using namespace std;
int main() 
{
	int n;cin>>n;
	while(n--)
	{
		string x;cin>>x;
		string r1="";int i=0;
		for(i=0;i<x.length();i++)
		{
			if(x[i]=='0') r1+="0000";
			else if(x[i]=='1') r1+= "0001";
			else if(x[i]=='2') r1+= "0010";
			else if(x[i]=='3') r1+= "0011";
			else if(x[i]=='4') r1+= "0100";
			else if(x[i]=='5') r1+= "0101";
			else if(x[i]=='6') r1+= "0110";
			else if(x[i]=='7') r1+= "0111";
			else if(x[i]=='8') r1+= "1000";
			else if(x[i]=='9') r1+= "1001";
			else if(x[i]=='A') r1+= "1010";
			else if(x[i]=='B') r1+= "1011";
			else if(x[i]=='C') r1+= "1100";
			else if(x[i]=='D') r1+= "1101";
			else if(x[i]=='E') r1+= "1110";
			else if(x[i]=='F') r1+= "1111";
		}
		if((r1.length()%3)==1) r1="00"+r1;
		else if((r1.length()%3)==2) r1="0"+r1;
		x=r1;
		int show=0;
		for(int i=0;i<x.length();i+=3)
		{
			int y=((x[i]-'0')*4+(x[i+1]-'0')*2+(x[i+2]-'0')*1);
			if(y==0&&show==0) continue;
			cout<<y;
			show=1;
		}cout<<endl;
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值