思路:十进制转十六进制,
获取十进制数%16的值
判断获取的值是在0~9还是10~15
定义一个string变量,用来拼接所获取值的字符,就是9+‘0‘,数字转字符
如果值再10~15之间,则用获取的值-10+’A‘,然后在和string变量拼接
注意点是,每次获取的值转换成字符后和string拼接的时候要写在前面,具体可以看代码
#include <iostream>
#include <string>
using namespace std;
string toHexString(int n);
int main() {
int n;
cin >> n;
string hexStr = toHexString(n);
cout << hexStr << endl;
return 0;
}
string toHexString(int n) {
// write your code here......
string str="";
while(n!=0)
{
int temp=n%16;
if(temp>=0 && temp<=9)
{
char c=temp+'0';
str=c+str;
}
else if(temp>=10 && temp<=15)
{
char c=temp-10+'A';
str=c+str;
}
else{
}
n=n/16;
}
return str;
}

京公网安备 11010502036488号