进制转换

1、十进制转26进制

26进制为[a-z]->[0-25]

#include <cstdlib>  
#include <iostream>  
#include <string>  
#include <sstream>
#include <math.h>
using namespace std;
int main()
{
	string az("zabcdefghijklmnopqrstuvwxy");
	string dest,i;
	int number, number2;
	getline(cin, i);
	if(isdigit(i[0])){
		stringstream ss;
		ss << i;
		ss >> number;
		do
		{
			dest = az[number % 26] + dest;
			number /= 26;
		} while (number != 0);
		cout << dest << endl;
	}
	else{
		if (i.size() > 6) return 0;
		int output=0;
		for (int num1 = (i.size() - 1),num2=0; num1 >= 0; --num1,++num2)
                {
			int j = (i[num1] - 'a')+1;
			output += j*pow(26, num2);
		}
		cout << output  << endl;
	}
	system("PAUSE");
	return 0;
}

据说上面的是17年华为笔试第二题,今天招行网络科技笔试第一题与其类似,只是增加了小数 

引申下来,任意进制转十进制以及十进制转任意进制,2和3部分代码参考:https://blog.csdn.net/qq_38492462/article/details/78254363

2、任意进制转十进制

任意进制转十进制,都是乘以基数的多少次方,然后相加,代码如下

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int r,i=0,ans=0;
    string n;
    cin>>r>>n;//R表示进制,N表示要转换的数,ans表示要转换的结果。
    while(n.size()!=i)
    {
        ans*=r;       //我这里是把1看成0,把0看成1来算的。这样比较方便。其实都一样。
        ans+=n[i]-'0';
        i++;
    }
    cout<<ans<<endl;
    return 0;
 

3、十进制转任意进制

一般算法都是除以基数,然后倒着取数,与栈很相似,代码如下

#include<iostream>
#include<stack>
using namespace std;

int main()
{
    int r,n;
    stack<int> s;
    cin>>n>>r;
    while(n)
    {
        s.push(n%r);
        n/=r;
    }
    while(!s.empty())
    {
        switch(s.top())
        {
            case 10:cout<<'A';break;
            case 11:cout<<'B';break;
            case 12:cout<<'C';break;
            case 13:cout<<'D';break;
            case 14:cout<<'E';break;
            case 15:cout<<'F';break;//这些都是为了能转化为十六进制。
            default:cout<<s.top();break;
        }
        s.pop();
    }
    return 0;
 } 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值