LeetCode 504. Base 7 (C++)

时间:2023-03-09 00:05:01
LeetCode 504. Base 7 (C++)

题目:

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进制数,求十进制表示,注意返回的是字符串。

进制转换没什么好说的,注意这道题测试用例是有负数的,且返回值是字符串,记得转成字符串形式。

程序:

class Solution {
public:
string convertToBase7(int num) {
if(num == ) return "";
string res;
int n = abs(num);
while(n){
res = to_string(n%) + res;
n /= ;
}
if(num < )
return "-"+res;
else
return res;
}
};