您的位置:首页 > 其它

uva 1590

2015-09-13 11:20 218 查看
十进制与二进制的转换, 简单题

但是刚写起来思路太乱, 改了好多遍, 所以写得比较丑, 仅供娱乐

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <list>
using namespace std;
const int MAXN = 60;
const int SIZE = 6;
typedef long long LL;

/*
uva 1590
关键 : 十进制(字符串)转二进制问题
*/

inline void Dec2Bi(int dec,char *result){
for(int i=0; i<8; i++){
if( dec & 1 ){
result[7-i] = '1';
}else{
result[7-i] = '0';
}
dec >>= 1;
}
result[8] = '\0';
}

string Bi2Dec(char bi[MAXN]){
string res;
for(int i=0; i<4; i++){
int sum = 0;
for(int j=0; j<8; j++){
if( bi[i*8+j]=='1' ){
sum += (1<<(7-j));
}
}
char tmp[10];
sprintf(tmp,"%d",sum);
res += tmp;
if( i!=3 ) res += ".";
}
return res;
}

int Compare(string a,string b){
int i;
for(i=0; i<a.length(); i++){
if( a[i]!=b[i] ){
break;
}
}
return i;
}

void test(){
unsigned int sum = pow(2,9)-1;
cout << (sum<<8) << endl;
cout << (sum<<16) << endl;
cout << (sum<<24) << endl;
}

int main(){
int m,t;
unsigned int dec;
char tmp[9];
string ip;
vector<string> input;
while( scanf("%d",&m)!=EOF ){
ip.clear();
input.clear();
while( m-- ){
t = 4;
ip.clear();
while( t-- ){
scanf("%d",&dec);
getchar();
Dec2Bi(dec,tmp);
ip += tmp;
}
input.push_back(ip);
}
char mask[MAXN]={0},res[MAXN]={0};
strcpy(mask,input[0].c_str());
for(int i=1; i<input.size(); i++){
mask[Compare(mask,input[i])] = '\0';
}

int masklen = strlen(mask);
strcpy(res,input[0].c_str());
for(int i=masklen; i<32; i++){
res[i] = '0';
}
cout << Bi2Dec(res) << endl;

strcpy(res,input[0].c_str());
int i=0;
for(i=0; i<masklen; i++){
res[i] = '1';
}
for( ; i<32; i++){
res[i] = '0';
}
cout << Bi2Dec(res) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: