题目要求:
给定一个整数 num
,将其转化为 7 进制,并以字符串形式输出。
C++源码:
#include "stdafx.h"
#include <String>
using namespace std;
string convertToBase7(int num) {
int tempNum = num;
char t;
string str;
if (tempNum == 0) return "0";
if (tempNum<0)
{
tempNum = -tempNum;
}
while (tempNum >= 7)
{
t = (tempNum % 7);
tempNum /= 7;
str.insert(0, to_string(t));
}
t = tempNum;
str.insert(0, to_string(t));
if (num<0)
{
str.insert(0, "-");
}
return str;
}
int _tmain(int argc, _TCHAR* argv[])
{
string st = convertToBase7(7);
printf(st.c_str());
printf("\n");
st = convertToBase7(14);
printf(st.c_str());
printf("\n");
st = convertToBase7(700);
printf(st.c_str());
printf("\n");
st = convertToBase7(777);
printf(st.c_str());
printf("\n");
return 0;
}
运行的结果: