一、题目
Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100
Output: “202”
Example 2:
Input: num = -7
Output: “-10”
Constraints:
-107 <= num <= 107
二、题解
class Solution {
public:
string convertToBase7(int num) {
if(num == 0) return "0";
int flag = false;
if(num < 0){
num = -num;
flag = true;
}
string res = "";
while(num > 0){
res += (num % 7 + '0');
num /= 7;
}
reverse(res.begin(),res.end());
if(flag) return "-" + res;
else return res;
}
};