您的位置:首页 > 其它

[Leetcode] 504. Base 7 解题报告

2017-12-07 12:15 309 查看
题目

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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: