给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
注意: 输入范围是 [-1e7, 1e7] 。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/base-7 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
所以(185)10 =(271)8 。 除以N,留下余数,所有余数逆序即是答案
class Solution {
public:
string convertToBase7(int num) {
if(num == 0)
return "0";
bool negative = (num < 0);
num = abs(num);
string ans;
while(num)
{
ans.append(to_string(num%7));//余数
num /= 7;
}
if(negative)
ans.push_back('-');
reverse(ans.begin(), ans.end());//逆序
return ans;
}
};