十六进制转换成八进制。不知道为何错了???

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <ctype.h>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
	int n,i,l;
	char s[100005];
	cin>>n;
	getchar(); 
	while (n--)
	{
		gets(s);
		//puts(s);
		l=strlen(s);
		int k=16;
		__int64 a=0;
		if ( isalpha(s[l-1]) ) a+=s[l-1]-'A'+10;
		else a+=s[l-1]-'0';
		for (i=l-2;i>=0;i--)
		{
			int h;
			if (isalpha(s[i])) h=k*(s[i]-'A'+10);
				else h=k*(s[i]-'0');
			k*=16;
			a+=h;
		}
		char g[100010];
		itoa(a,g,8);
		printf("%s\n",g);
	}
	return 0;
}

回来无聊看了看这题,用一种二进制进位的方法解决了。主要是16进制一个字符占4位,8进制一个字符占3位,嗯,就这样。AC版代码。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int f(char c)
{
	if ('A'<=c)
		return c-'A'+10;
	return c-'0';
}
char s[1000100];
int a[1000100];
int main()
{
	int T;
	freopen("in.txt","r",stdin);
//	freopen("out.txt","w",stdout);
	scanf("%d",&T);
	getchar();
	while (T--)
	{
		scanf("%s",s);
		int t=0,w=0,num=0;
		int l=strlen(s);
		for (int i=l-1;i>=0;i--)
		{
			int k=f(s[i]);
			if (t==0)
			{
				a[num++]=k & 7;
				w=k>>3;
				t=(t+1)%3;
			}
			else if (t==1)
			{
				k=(k<<1)+w;
				a[num++]=k & 7;
				w=k>>3;
				t=(t+1)%3;
			}
			else
			{
				k=(k<<2)+w;
				a[num++]=k & 7;
				a[num++]=k>>3;
				w=0;
				t=(t+1)%3;
			}
		}
		if (w) a[num++]=w;
		int j=num-1;
		while (a[j]==0) j--;
		for (int i=j;i>=0;i--)
			printf("%d",a[i]);
		cout<<endl;
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值