【習題練習】十進制轉15進制

題目描述:

       輸入一個十進制整數,將這個數轉化成對應的十五進制數(在十五進制中,A表示10,B表示11,C表示12,D表示13,E表示14),請寫出轉換程序。

代碼實現:

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <iterator>
#include <time.h>
#include <string>
#include <math.h>
#include <utility>
#include <algorithm>
using namespace std;

void deal(string& ans_str, int remainder)
{
	char arr[5];
	auto it = ans_str.begin();
	if (remainder < 10)
	{
		sprintf_s(arr, "%d", remainder);
		ans_str.insert(it, arr[0]);
		return;
	}

	char brr[] = "ABCDE";
	for (int i = 10; i < 15; i++)
	{
		if (remainder == i)
		{
			ans_str.insert(it, brr[i % 10]);
			break;
		}			
	}	
}

void transform(long long value)
{
	string ans_str;
	if (value == 0)
	{
		cout << "0" << endl;
		return;
	}

	while (value)
	{
		int remainder = value % 15;
		deal(ans_str, remainder);
		value /= 15;
	}

	copy(ans_str.begin(), ans_str.end(), ostream_iterator<char>(cout));
	cout << endl;
}

int main()
{
	while (1)
	{
		long long tmp;  
		cin >>tmp;
		transform(tmp);
	}	
	return 0;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章