最近各种笔试面试,碰到了大数的进制转换问题,给一串很长很长的十进制数,要转换成16进制,用常规方法肯定不行的,得换个思路。于是在网上找到了前辈分享的方法:
思想掌握了,咱就来敲一遍代码试验一下吧:
#include<iostream>
#include<stack>
#define notation1 10
#define notation2 16
using namespace std;
char Table16[]="0123456789ABCDEF";
//
//将十进制字符串 转换为16进制
//
//*/
void CharToInt(char *Input,int *num)
{
if(Input==NULL) return;
while(*Input!='\0')
{
if(*Input>='0'&&*Input<='9')
*num++=*Input-'0';
Input++;
}
}
void ConvertCore(int *num,int len )
{
int firstNum0=0,plus; //firstNum0标记着num数组第一个非0的位置,若==len,则表示结束转换
stack<int> residue;
while(firstNum0!=len)//=First0ofnum(num,len))!=len)
{
plus=0;
int flag=false;
for(int i=firstNum0;i<len;i++)
{
int tmp=(plus*notation1+num[i]);
plus=tmp%notation2;
num[i]=tmp/notation2;
if(num[i]!=0) flag=true; //flag标记有没有出现非0的数
if(num[i]==0&&flag!=true) firstNum0++; //若之前没有出现非0的数且当前数为0,则firstNum0++,例如 00001010,后面两个0不会起作用的
}
residue.push(plus);
}
while(!residue.empty()) //倒序查表输出
{
cout<<Table16[residue.top()];
residue.pop();
}
cout<<endl;
}
int main()
{
char str[1000];
cout<<"please input the dec num:\n";
cin>>str;
int len=strlen(str);
int *num=new int[len];
CharToInt(str,num);
for(int i=0;i<len;i++) //测试一下是否有问题
cout<<num[i];
cout<<endl;
ConvertCore(num,len);
return 0;
}