题目
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
注意: 输入范围是 [-1e7, 1e7] 。
C++解法
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string convertToBase7(int num) {
string result = "";
int value = abs(num);
do {
result.push_back('0' + value % 7);
} while (value /= 7);
if (num < 0) result.push_back('-');
reverse(result.begin(), result.end());
return result;
}
};
int main(int argc, const char * argv[]) {
Solution solution;
cout << solution.convertToBase7(100) << endl;
cout << solution.convertToBase7(-7) << endl;
return 0;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/base-7
网友评论