1.题目描述
Given an integer, return its base 7 string representation. 给一个十进制整数(-10^7,10^7),转成7进制表示,返回string 例: Input: 100 Output: “202” Input: -7 Output: “-10”
2.分析
正常进制转换。先判断符号。
3.代码
c++
string convertToBase7(
int num) {
if (num ==
0)
return "0";
vector<char> base7;
bool isnegative =
false;
if (num <
0) {
num = -num;
isnegative =
true;
}
while (num >
0) {
base7.push_back(num %
7+
'0'-
0);
num /=
7;
}
if (isnegative)
base7.push_back(
'-');
return string(base7.rbegin(), base7.rend());
}