题目:
Given an integer, return its base 7 string representation.
Example 1:
Input: 100 Output: "202"
Example 2:
Input: -7 Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
思路:
练手题目,哈哈。不过需要注意特殊情况:1)num < 0;2)num == 0。算法的时间复杂度应该是O(log_{7}n)。其实也就是O(logn),因为以7为底的对数和以2为底的对数是线性关系。
代码:
class Solution {
public:
string convertToBase7(int num) {
if (num < 0) {
return "-" + convertToBase7(-num);
}
else {
string ret;
while (num != 0) {
ret.push_back(num % 7 + '0');
num /= 7;
}
reverse(ret.begin(), ret.end());
return ret.length() == 0 ? "0" : ret;
}
}
};
本文介绍了一个简单的算法,用于将十进制整数转换为其七进制表示形式的字符串。通过递归方法处理负数,并使用循环来计算正数的七进制表示。
302

被折叠的 条评论
为什么被折叠?



