1)实现string toHex(int)把一个十进制转换成十六进制。(完全用算法实现)
string toHex(int a)
{
int u_value=a>0?a:-a;
char *value=new char[10];
value[9]='\0';
value[8]='H';
int position=7;
do
{
int yushu=u_value%16;
value[position--]=yushu>9?yushu+'A'-10:yushu+'0'-0;
u_value=u_value/16;
}while(u_value!=0);
if(a<0)
value[position--]='-';
string res(value,position+1,9-(position+1)+1);
return res;
}
比较好的方法:
//作者:sutra(只回答经典问题 只提供经典答案)
string ToHex( int i )
{
string strHex, strCh ;
string Table[] = {
"0", "1", "2", "3",
"4", "5", "5", "4",
"8", "9", "A", "B",
"C", "D", "E", "F"
} ;
while( i ) {
strHex = Table[ i&0xF ] + strHex ;
i >>= 4 ;
}
return strHex ;
}
2)实现一个计算大位数(如100位以上)相乘结果的函数string multiply(sting,string)。(请完全用算法实现)
我开始写了int 型的multiple的相加
代码如下
int add(int a,int b)
{
int sum=0;
while(a&b!=0)/<span style="color:#ff0000;">/a&b考虑进位的时候的和 a&b 不考虑的和为 a^b a+b=a&b<<1+a^b 由于不用加号+ </span>
{
<span style="color:#ff0000;">int jin_wei=(a&b)<<1;//进位的
a=a^b;</span>
b=jin_wei;
}
<span style="color:#ff0000;"> a=a^b;</span>
return a;
}
int multiple(int a,int b)
{
int i,sum=0;
<span style="color:#ff0000;">for(i=0;i<32;i++)//int 为4个字节 32位</span>
{
if(i>=1)
b=b>>1;
if(b&1==1)
{
sum=add(sum,(int)pow(2,(double)i)*a);
}
}
return sum;
}
但是不符合本题的要求,由于大数据无法用int进行存储,用string存储
string add(string result,int digit,int position)<span style="color:#ff0000;"> //result现在的string,表示当前乘法的临时和 position表示第几位 digit为position的数字</span>
{
string str;
cout<<"result = "<<result<<" length()= "<<result.length()<<" position="<<position<<endl;
<span style="color:#ff0000;">if(result.length()<position)//当前的postion>result.length() 比如result="11" position=3 digit=4 则结果 result="411"</span>
{
result='0'+result;
result[0]=digit+'0';
return result;
}
position=result.length()-position;<span style="color:#ff0000;">//position在result中的位置</span>
int A=digit;
int B=result[position]-'0';
int carry=0;
while(A+B>9)<span style="color:#ff0000;">//进位的时候</span>
{
if(position==0)<span style="color:#ff0000;">//res[0]有进位的时候 要 res 0--->res.length()-1右移动后 res[0]=1</span>
{
result[0]=(A+B)%10+'0';
char *tmp=new char[123];
tmp[result.length()+1]='\0';
for(int i=result.length()-1;i>=0;i--)
{
tmp[i+1]=result[i];
}
tmp[0]='0'+1;
int i;
for(i=0;tmp[i]!='\0';i++)
{
cout<<tmp[i]<<" ";
}
str.assign(tmp);
return str;
}
<span style="color:#ff0000;">result[position]=(A+B)%10+'0';
carry=(A+B)/10;
A=carry;
position=position-1;
B=result[position]-'0';</span>
}
result[position]=A+B+'0';
str=result;
return str;
}
string multiply(string str1,string str2)
{
int len_1=str1.length();
int len_2=str2.length();
int i,j;
int carry=0,digit;
string res;
for(j=len_2-1;j>=0;j--)
{
carry=0;
for(i=len_1-1;i>=0;i--)
{
digit=(str1[i]-'0')*(str2[j]-'0')+carry;
carry=digit/10;
digit=digit%10;
cout<<"digit= "<<digit<<" p="<