带小数的二进制与十六进制互相转换(超暴力版)

啊,就写着玩了,很暴力

如果转换后的字符串是回文串,顺便输出个 Beautiful


#include 
#define endl '\n'
using namespace std;
typedef long long ll;
typedef long double ld;
//typedef __int128 bll;
const int maxn = 1e6 + 100;
const int mod = 1e9+7;
const ll inf = 1e18;

ll dis = -1;
string tmp[16] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
mapM;

string slove(ll base,string str)
{
	string ans;
	bool flag = false;
	for(ll i = 0; i < str.size(); ++i)
	{
		if(str[i] == '.')
		{
			flag = true;
			dis = i;
			break;
		}
	}
	
	if(base == 2)
	{
		if(flag)
		{
			ll num1 = 4-(dis%4),num2 = 4-(str.size() - dis - 1)%4;
			num1 = num1%4;
			num2 = num2%4;
			
			
			for(ll i = 0; i < num1; ++i)
				str = "0" + str;
			for(ll i = 0; i < num2; ++i)
				str = str + "0";
		}
		else
		{
			ll num1 = 4 - (str.size()%4);
			num1 = num1%4;
			
			for(ll i = 0; i < num1; ++i)
				str = "0" + str;
		}
		
		ll num = 0;
		string t;
		for(ll i = 0; i < str.size(); ++i)
		{
			if(str[i] == '.')
			{
				num = 0;
				ans = ans + ".";
			}
			else
			{
				num++;
				t = t + str[i];
			}
			
			if(num == 4)
			{
				num = 0;
				ans = ans + M[t];
				t = "";
			}
		}	
	}
	else if(base == 16)
	{
		for(ll i = 0; i < str.size(); ++i)
		{
			if(str[i] == '.')
			{
				ans = ans + ".";
			}
			else
			{
				string s(1,str[i]);
				ans = ans + M[s];
			}
				
		}
	}
	return ans;
}

bool pan(string str)
{
	int len = str.length();
    const char *p = str.c_str();
    int n = 0;
    for(int i = 0; i < len / 2; i++)
    {
        if(p[i] == p[len - 1 - i])
        {
            continue;
        }
        else { n = 1; break; }
    }
    if (n == 1)
    	return false;
    else 
    	return true;
}

int main()
{
	//ios::sync_with_stdio(false);
	//cin.tie(0),cout.tie(0);
	
	M["0"] = "0000";M["1"] = "0001";M["2"] = "0010";M["3"] = "0011";
	M["4"] = "0100";M["5"] = "0101";M["6"] = "0110";M["7"] = "0111";
	M["8"] = "1000";M["9"] = "1001";M["A"] = "1010";M["B"] = "1011";
	M["C"] = "1100";M["D"] = "1101";M["E"] = "1110";M["F"] = "1111";
	
		
	for(ll i = 0; i < 16; ++i)
	{
		M[ M[tmp[i]] ] = tmp[i];
	}
	
	string str;
	ll base;
	while(cin >> base >> str)
	{
		dis = -1;
		bool flag;
		
		string ans = slove(base,str);
		flag = pan(ans);
		
		if(dis == -1)
		{
			while(ans[0] == '0')
			{
				ans.erase(0,1);
			}
		}
		else
		{
			//cout << "lala" << endl;
			while(ans[0] == '0' && ans[0] != '.' )
			{
				ans.erase(0,1);
			}
			
			ll t = ans.size()-1;
			while( ans[t] == '0' && ans[t] != '.' )
			{
				ans.erase(t,1);
				t--;
			}
		}
		
		//cout << ans << endl;
		if(ans == "" || ans == ".")
			ans = "0";
		
		if(ans[ans.size()-1] == '.')
			ans.erase(ans.size()-1,1);
		
		if(ans[0] == '.' && ans.size() > 1)
			ans = "0" + ans;
		
		if(flag)
			cout << "Beautiful " << ans << endl;
		else
			cout << ans << endl;
	}
	
	return 0;
}

 

你可能感兴趣的:(模板)