华为笔试题-进制转换

这篇博客介绍了如何编写一个程序,该程序能够接收一个十六进制数值的字符串输入,并将其转换成对应的十进制字符串。通过实例展示了从‘0xA’到‘10’的转换过程,同时提到了程序的初始版本和改进后的版本。
摘要由CSDN通过智能技术生成

写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。

输入例子1:
0xA
输出例子1:
10

//最开始写的

#include<iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;

int main()
{
	string str;
	while (cin >> str)
	{
		if (str[0] == '0' && str[1] == 'x')
		{
			string newStr;
			auto it = str.begin() + 2;
			while (it != str.end())
			{
				newStr.push_back(*it);
				it++;
			}
			str.clear();
			reverse(newStr.begin(), newStr.end());

			vector<int> ivec;
			it = newStr.begin();
			while (it != newStr.end())
			{
				if (*it >= '0' && *it <= '9')
				{
					ivec.push_back((*it - '0'));
				}
				else if (*it >= 'A' && *it <= 'F')
				{
					ivec.push_back((*it - 'A') + 10);
				}
				else if (*it >= 'a' && *it <= 'f')
				{
					ivec.push_back((*it - 'a') + 10);
				}
				++it;
			}

			int sum = 0;//数值型局部变量要赋初值!!!
			for (int i = 0; i<ivec.size(); ++i)
			{
				sum += ivec[i] * (int)(pow(16, i));
			}

			cout << sum << endl;
		}

	}

	return 0;
}

//改进

#include<iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;

int main()
{
	string str;
	while (cin >> str)
	{
		if (str[0] == '0' && str[1] == 'x')
		{
			string newStr = str.substr(2);
			vector<int> ivec;
			int sum = 0;//数值型局部变量要赋初值!!!
			auto it = newStr.begin();
			while (it != newStr.end())
			{
				int temp = 0;
				if (*it >= '0' && *it <= '9')
				{
					temp = *it - '0';
				}
				else if (*it >= 'A' && *it <= 'F')
				{
					temp = *it - 'A' + 10;
				}
				else if (*it >= 'a' && *it <= 'f')
				{
					temp = *it - 'a' + 10;
				}

				sum = sum * 16 + temp;
				++it;
			}
			cout << sum << endl;
		}

	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值