LeetCode 504. Base 7
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"
method 1: 模拟
注意进制转换的写法int
如何转换为char
,也可以用to_string()
转换为string
string convertToBase7(int num) {
if (num == 0) return "0";
int x = num > 0 ? num : -num;
string ret;
while (x) {
ret = char('0' + x % 7) + ret;
x /= 7;
}
if (num < 0) ret = '-' + ret;
return ret;
}
method 2: 递归
- 小于0,加个负号,再递归处理相反数
- 小于7,直接返回整数转成的字符串
- 大于7,除以7部分继续递归,模以7部分转成字符串
string convertToBase7(int num) {
if (num < 0) return "-" + convertToBase7(-num);
if (num < 7) return to_string(num);
return convertToBase7(num / 7) + to_string(num % 7);
}