文章目录
- toHexString(int n) 函数,输入整型数字n,返回 字符串string类。
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
using namespace std;
string toHexString(int n)
{
vector <int> v;
char m[15] = { '1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'A' ,'B' ,'C' ,'D' ,'E' ,'F' };
int over = 0;
for (int j = 1; over == 0; ++j)
{
int temp1 = (int)(n / pow(16, j));
if (temp1 == 0) over = 1;
int temp2 = n - temp1 * pow(16, j);
int l = 0;
vector <int>::iterator k;
for (k = v.begin(); k != v.end(); k++)
{
temp2 = temp2 - (*k) * pow(16, l);
l++;
}
temp2 = temp2 / pow(16, j - 1);
v.push_back(temp2);
}
int length = v.size();
char* s = new char[length + 1];
for (int i = 0; i < length; ++i)
s[i] = m[v[length - 1 - i] - 1];
s[length] = '\0';
string mys = s;
return mys;
}
int main()
{
int n;
cin >> n;
string hexStr = toHexString(n);
cout << hexStr << endl;
return 0;
}