[Leetcode] 504. Base 7 解题报告
2017-12-07 12:15
309 查看
题目:
Given an integer, return its base 7 string representation.
Example 1:
Example 2:
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;
}
}
};
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;
}
}
};
相关文章推荐
- 【LeetCode】Base 7 解题报告
- [Leetcode] 483. Smallest Good Base 解题报告
- LeetCode 483 Smallest Good Base 解题报告
- [LeetCode] Scramble String 解题报告
- leetCode解题报告5道题(九)
- leetCode解题报告之O(n)线性时间求最大子序列和(Maximum Subarray)
- [leetcode] 232. Implement Queue using Stacks 解题报告
- [leetcode] 296. Best Meeting Point 解题报告
- [leetcode] 350. Intersection of Two Arrays II 解题报告
- [Leetcode] 315. Count of Smaller Numbers After Self 解题报告
- [leetcode] 186. Reverse Words in a String II 解题报告
- 【LeetCode】Island Perimeter 解题报告
- LeetCode 3. Longest Substring Without Repeating Characters 解题报告
- 【LeetCode】784. Letter Case Permutation 解题报告
- [Leetcode] 46. Permutations 解题报告
- [Leetcode] 581. Shortest Unsorted Continuous Subarray 解题报告
- [LeetCode] Word Search 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- LeetCode: Combination Sum 解题报告
- [Leetcode] 475. Heaters 解题报告