541.七进制数
caution
题目
给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100
输出: "202"
示例 2:
输入: num = -7
输出: "-10"
提示:
-10^7 <= num <= 10^7
代码
class Solution {
public:
string convertToBase7(int num) {
const int N = 1e5 + 10;
char stk[N], tt = -1, res[N] = { '0' };
bool neg = num < 0;
num = abs(num);
do {
stk[++tt] = (num % 7) + '0';
num /= 7;
} while (num != 0);
if (neg) stk[++tt] = '-';
int len = tt;
for (int i = 0; i <= len; i++) res[i] = stk[tt--];
return res;
}
};