一、又一版 A+B
1、題目和要求
時間限制:1s,內存限制:32MB,特殊判題:否
2、總結
A、B不超過整型定義
,可以用int
存儲,但相加後可能會溢出,所以結果使用long
存儲(scanf、printf("%lld",result)
)。
3、代碼
#include <string>
#include <iostream>
using namespace std;
#define N 31
int main()
{
int m_result[N]; //存儲進制轉換後的數字
long d_result; //存儲十進制數字
int a,b;
int m;
cin>>m;
while(m!=0)
{
int i=0;
cin>>a>>b;
d_result = a+b;
while(d_result!=0)
{
m_result[i++]=d_result%m;
d_result = d_result/m;
}
for(int j=i-1; j>=0; j--)
{
cout<<m_result[j];
}
cout<<endl;
cin>>m;
}
return 0;
}
二、數制轉換
1、題目和要求
時間限制:1s,內存限制:32MB,特殊判題:否
2、總結
1)使用cin.get()!=EOF
實現循環輸入,使用cin.get();
接收多餘的回車,不然會多一次循環。
2)權重的另一種表示方式:int c=1
,c爲各個數位的權重,初始化爲1,之後每位權重都是前一位權重的a倍。
3)參考:
當字符爲小寫字母時,計算其代表的數字:x=input[i]-'0'+10
將數字轉換爲字符:output[i++] = (x<10) ? x+'0' : x-10+'A'
3、思路
數制轉換的思路:先轉爲10進制,再從10進制轉爲其他進制。
4、代碼
#include <math.h>
#include <string>
#include <iostream>
using namespace std;
string input;
int a2decimal(int a)
{
int i=0,result=0;
while(input[i]!='\0')
{
int zhi = input.length()-i-1;
if(input[i]>='a'&&input[i]<='f')
{
int value = input[i]-87;
result+=value*pow(a,zhi);
}
else if(input[i]>='A'&&input[i]<='F')
{
int value = input[i]-55;
result+=value*pow(a,zhi);
}
else
{
int value = input[i]-48;
result+=value*pow(a,zhi);
}
i++;
}
return result;
}
void decimal2b(int b,int result)
{
string output;
int i=0,t;
do
{
t=result%b;
result/=b;
if(t>9)
{
output[i++]=t+55;
}
else
{
output[i++]=t+48;
}
}
while(result!=0);
for(int j=i-1; j>=0; j--)
{
cout<<output[j];
}
cout<<endl;
}
int main()
{
int a,b;
do{
cin>>a>>input>>b;
cin.get();
decimal2b(b, a2decimal(a));
}while(cin.get()!=EOF);
return 0;
}