【2038】四位16进制数转化为10进制

Time Limit: 1 second
Memory Limit: 50 MB

【问题描述】

    输入一个4位16进制数,将它转化位10进制数并输出。

【输入】

    共1行;
    一个4位16进制数。

【输出】

    包含2行,第一行重写该4位16进制数。     第2行,dec:一个整数,表示转化的结果。

【输入样例】

    1a2b 


【输出样例】

    1a2b
    dec:6699

【题解】

1a2b的转化过程为

:先倒序 b2a1

a = 10 b =11

dec = 16^(0) * 11 + 16^(1) *2 + 16^(2)*10 + 16^(3)*1 = 6699'

模拟下这个过程就好

【代码】

#include <cstdio>
#include <string>
#include <iostream>

using namespace std;

const int maxn = 1000;

string s1;
int a[maxn],ans = 0;

void input_data()
{
	cin >> s1;
}

void get_ans()
{
	for (int i = 3;i >= 0;i--) //倒序存入整形数组 其中加入了预防大写字母的方案。 
		{
			if (s1[i] >= 'a' && s1[i] <= 'z')
					a[4-i] = s1[i] - 'a' + 10;
			if (s1[i] >= 'A' && s1[i] <= 'Z')
					a[4-i] = s1[i] - 'A' + 10;
			if (s1[i] >= '0' && s1[i] <= '9')
					a[4-i] = s1[i] - '0'; 
		}
	ans = a[1] + 16*a[2] + 16*16*a[3] + 16*16*16*a[4]; //有指出是4位 所以直接获取答案了。 
}

void output_ans()
{
	cout << s1 << endl;
	printf("dec:%d\n",ans);	
}

int main()
{
	input_data();
	get_ans();
	output_ans();
	return 0;	
}


 

posted @ 2017-10-06 19:23  AWCXV  阅读(1740)  评论(0编辑  收藏  举报