Given an integer
num
, return a string of its base 7 representation.
示例
示例 1:
输入: num = 100
输出: "202"
示例 2:
输入: num = -7
输出: "-10"
解题
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;
}
};
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/18717.html