题目:
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].
翻译:
给定一个数字,返回它的7进制字符串表示。
例子 1:
输入: 100 输出: "202"
例子 2:
输入: -7 输出: "-10"
注意: 输入的范围是 [-1e7, 1e7].
思路:
不断模7操作,注意 正负号。
C++(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string convertToBase7(int num) {
if (num == 0) return "0";
bool positive = num > 0;
string res = "";
while (num != 0) {
res = to_string(abs(num % 7)) + res;
num = num / 7;
}
return positive ? res : "-" + res;
}
};
int main()
{
Solution s;
int num = 100;
string result;
result = s.convertToBase7(num);
cout << result;
return 0;
}