題目1138:進制轉換
題目描述:
将一個長度最多為30位數字的十進制非負整數轉換為二進制數輸出。
輸入:
多組資料,每行為一個長度不超過30位的十進制非負整數。
(注意是10進制數字的個數可能有30個,而非30bits的整數)
輸出:
每行輸出對應的二進制數。
樣例輸入:
1
3
8
樣例輸出:
1
11
1000
#include
#include
#define false 0
#define true 1
char src[40];
int tar[100];
int cha=0;
int lenof(char tar[])
{
int i=0;
int len=0;
while(tar[i]!='\0') {
i++;
len++;
}
return len;
}
int isZero(char src[])
{
int i;
for ( i=lenof(src)-1; i>=0; i--) {
if (src[i] != '0') {
return false;
}
}
return true;
}
void ToBin(char src[])
{
int i=0;
int j=0;
int len=lenof(src);
while(!isZero(src)) {
int temp=0;
int yu=0;
for(i=0; i
if(i==len-1) {
temp = (yu*10 + (src[i]-'0'))/2 ;
yu=(yu*10 + (src[i]-'0'))%2;
src[i]= '0'+temp;
tar[j]=yu;
j++;
} else {
temp = (yu*10 + (src[i]-'0'))/2 ;
yu=(yu*10 + (src[i]-'0'))%2;
src[i]='0'+temp;
}
}
}
cha=j;
}
int main()
{
int i=0;
memset(tar,0,sizeof(tar));
while(scanf("%s",src)!=EOF) {
if(isZero(src)) printf("0");
else {
ToBin(src);
for(i=cha-1; i>=0; i--) {
printf("%d",tar[i]);
}
}
printf("\n");
cha=0;
}
return 0;
}
附上網上看到的别人的C++代碼
#include
#include
#include
#include
using namespace std;
char binvec[1001];
void tenToBin(string str)
{
int j=0;
int sum=1;
int len=str.size();
while (sum) {
sum=0;
for (int i=0; i
int temp=(str[i]-'0')/2;
sum+=temp;
if (i==len-1) {
binvec[j++]=(str[i]-'0')%2+'0';
} else {
str[i+1]=str[i+1]+(str[i]-'0')%2*10;//算出下一個被除數
}
//記錄該次得出的商
str[i]=temp+'0';
}
}
}
void resout()
{
//逆序
int len1=strlen(binvec);
for (int i=0,j=len1-1; i
char temp=binvec[j];
binvec[j]=binvec[i];
binvec[i]=temp;
}
cout<
}
int main()
{
string str;
while(cin>>str) {
memset(binvec,'\0',sizeof(binvec));
tenToBin(str);
resout();
}
return 0;
}